【发布时间】:2019-03-13 12:36:59
【问题描述】:
我是 nodeJS 的新手。我正在尝试将 index.html 页面加载到我的 8080 端口上并拥有以下内容:
var http = require('http');
var fs = require('fs');
var PORT = 8080;
function home(req, res) {
if(req.url == '/'){
fs.readFile('index.html', function read (err, data) {
res.writeHead(200, {'Content-type' : 'text/html'});
res.write(data);
res.end();
});
}
};
var server = http.createServer(function (req, res) {
home(req, res);
});
server.listen(PORT);
我在同一目录中有 3 个文件:index.html、style.css、server.js。我启动服务器,直到我按下 cntrl + c 后页面才会加载。这是为什么呢?
【问题讨论】:
-
是的,你错过了
res.end()。尽管我建议使用 express 而不是重新发明轮子。 -
是的,我添加了 res.end() 页面仍然无法加载。
-
使用上面的代码,包括
res.end(),访问localhost:8080对我来说效果很好并显示index.html。
标签: javascript node.js server localhost