我在 Node 中的 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");
最佳答案
您没有指定内容类型,如果您尝试:
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 格式显示错误页面,您还需要更新该内容类型。
关于javascript - Node.js app.js 不显示 HTML 页面而是显示 HTML 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21160873/