我的app.js在节点中没有显示我的html页面而是我的html代码有问题。我真的不知道该怎么做,所以一些帮助将不胜感激。我希望能够从我的公共文件夹加载html,javascript和css。 这是我的app.js代码:
var http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs")
http.createServer(function(request, response) {
var uri = url.parse(request.url).pathname
, filename = path.join(process.cwd(), uri);
path.exists(filename, function(exists) {
if(!exists) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
return;
}
if (fs.statSync(filename).isDirectory()) filename += 'public/index.html';
fs.readFile(filename, "binary", function(err, file) {
if(err) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
return;
}
response.writeHead(200);
response.write(file, "binary");
response.end();
});
});
}).listen(process.env.PORT, process.env.IP);
console.log("Static file server running./\CTRL + C to shutdown");
答案 0 :(得分:1)
如果您尝试:
,则不指定内容类型fs.readFile(filename, "binary", function(err, file) {
if(err) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
return;
}
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(file, "binary");
response.end();
});
});
}).listen(process.env.PORT, process.env.IP);
那应该有用。如果要在html中显示错误页面,您还需要更新该内容类型。