问题描述
我正在设计我的第一个Web应用程序,已经编写了相当一部分的前端,现在我想做一个非常简单的后端来开始实现某些功能。 最近几天,我花了很多时间来学习有关有效的后端开发和其他各种事情的知识,但是我遇到了一个巨大的问题。 我从根本上不了解如何附加我的前端和后端(我想使用nodejs)。
我想要的就是使用浏览器转到localhost:8080并自动查看带有前端的html文档,然后在前端代码中使应用程序与服务器通信(以获取json信息或指示服务器向数据库中添加内容)或类似的东西)。
1楼
在系统中安装节点之后。
资料夹结构:
将文件保存在应用程序文件夹内的公共文件夹中
导航到Terminal
或Command Prompt
应用程序文件夹:
然后创建一个文件作为package.json
并在其中保留以下代码:
{
"name" : "YourAppName",
"version" : "0.0.1",
"description" : "App description",
"dependencies" : {
"mime" : "~1.2.7"
}
}
然后回到终端并运行npm install
然后将文件创建为server.js
并在其中保留以下代码:
var http = require("http");
var fs = require("fs");
var path = require("path");
var mime = require("mime");
var cache = {};
function send404(responce){
responce.writeHead(404,{"content-type":"text/plain"});
responce.write("Error 404: resourse not found");
responce.end()
}
function sendFile(responce,filePath,fileContents){
responce.writeHead(200,{"content-type": mime.lookup(path.basename(filePath))});
responce.end(fileContents);
}
function serveStatic(responce,cache,abspath){
if(cache[abspath]){
sendFile(responce,abspath,cache[abspath]);
}else{
fs.exists(abspath,function(exists){
if(exists){
fs.readFile(abspath,function(err,data){
if(err){
send404(responce);
}else{
cache[abspath] = data;
sendFile(responce,abspath,data);
}
})
}else{
send404(responce)
}
})
}
}
var server = http.createServer(function(request,responce){
var filePath = false;
if(request.url == '/'){
filePath = 'public/index.html';
}else{
filePath = 'public'+request.url;
}
var abspath = './'+filePath;
serveStatic(responce,cache,abspath);
})
server.listen(8080,function(){
console.log("server running on 3000");
})
**这段代码可帮助您开始使用Node js,以便更好地理解 。
也要了解有关mime
模块的信息,此处已在使用它。
2楼
您可以使用免费的云服务,例如 。 这个
3楼
您可以使用Grunt并使用Connect插件,创建一个简单的服务器,足以开发纯JS Web应用程序。
使用Grunt基本上需要2个文件
-
package.json
-
Gruntfile.js
package.json
定义了Grunt运行所需的依赖项。
在您的情况下,它将包括
-
grunt
-
grunt-contrib-connect
(用于设置服务器的插件)`
根据您的要求,它可能还包括其他依赖项。
Gruntfile.js
定义了依赖项的配置。
在您的情况下,应如何设置服务器。
如果您使用的不是grunt-contrib-connect
插件,那么您也应该对其进行配置。
参考: