我想在我的Express/Node服务器上模拟一个404错误。我该怎么做呢?
发布于 2013-05-08 18:49:36
从Express4.0开始,就有了专门的sendStatus
function
res.sendStatus(404);
如果您使用的是早期版本的Express,请改用status
function。
res.status(404).send('Not found');
发布于 2015-10-24 04:09:02
Express 4.x的更新答案
与在旧版本的Express中使用res.send(404)
不同,新的方法是:
res.sendStatus(404);
Express将发送一个带有“找不到”文本的非常基本的404响应:
HTTP/1.1 404 Not Found
X-Powered-By: Express
Vary: Origin
Content-Type: text/plain; charset=utf-8
Content-Length: 9
ETag: W/"9-nR6tc+Z4+i9RpwqTOwvwFw"
Date: Fri, 23 Oct 2015 20:08:19 GMT
Connection: keep-alive
Not Found
发布于 2011-12-06 07:48:36
根据我将在下面发布的网站,这一切都是你如何设置你的服务器。他们展示的一个例子是:
var http = require("http");
var url = require("url");
function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
route(handle, pathname, response);
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
以及它们的路由函数:
function route(handle, pathname, response) {
console.log("About to route a request for " + pathname);
if (typeof handle[pathname] === 'function') {
handle[pathname](response);
} else {
console.log("No request handler found for " + pathname);
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not found");
response.end();
}
}
exports.route = route;
这是一种方法。http://www.nodebeginner.org/
从另一个站点,他们创建一个页面,然后加载它。这可能是你想要的更多东西。
fs.readFile('www/404.html', function(error2, data) {
response.writeHead(404, {'content-type': 'text/html'});
response.end(data);
});
https://stackoverflow.com/questions/8393275
复制相似问题