[英]Node.js app.js not displaying HTML page but HTML code instead
我在節點中的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顯示錯誤頁面,則也將要更新該內容類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.