我正在使用 node.js,我想知道如何显示 404.html 而不是“404 Not Found”消息。
这是我的 server.js:
var http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs")
port = process.argv[2] || 8888;
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/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(parseInt(port, 10));
console.log("Static file server running at\n => http://localhost:" + port + "/\nCTRL + C to shutdown");
正如你所看到的,它只是一个静态文件服务器,我没有使用express.js或任何东西。
H i ,
在您的 404 案件中
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
您可以更改为
response.writeHead(404, {"Content-Type": "text/html"});
response.write(HTMLDATA);
response.end();
'HTML数据'可以是 HTML 字符串,也可以是对您收集的文件的引用。
response.writeHead()
始终设置在response.write()
.
另请参阅我们已将响应类型设置为“text/html”
http://nodejs.org/api/http.html#http_class_http_serverresponse
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)