Javascript 如何使用 Express/Node 以编程方式发送 404 响应?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8393275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to programmatically send a 404 response with Express/Node?
提问by Randomblue
I want to simulate a 404 error on my Express/Node server. How can I do that?
我想在我的 Express/Node 服务器上模拟 404 错误。我怎样才能做到这一点?
回答by Drew Noakes
Nowadays there's a dedicated status
functionfor this on the response object. Just chain it in somewhere before you call send
.
现在在响应对象上有一个专门的status
功能。只需在调用之前将其链接到某个地方即可send
。
res.status(404) // HTTP status 404: NotFound
.send('Not found');
回答by Brad
Updated Answer for Express 4.x
Express 4.x 的更新答案
Rather than using res.send(404)
as in old versions of Express, the new method is:
res.send(404)
新方法不是在旧版本的 Express 中使用,而是:
res.sendStatus(404);
Express will send a very basic 404 response with "Not Found" text:
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
回答by rossipedia
You don't have to simulate it. The second argument to res.send
I believe is the status code. Just pass 404 to that argument.
你不必模拟它。res.send
我相信的第二个参数是状态代码。只需将 404 传递给该参数即可。
Let me clarify that: Per the documentation on expressjs.orgit seems as though any number passed to res.send()
will be interpreted as the status code. So technically you could get away with:
让我澄清一下:根据expressjs.org 上的文档,似乎传递给的任何数字都res.send()
将被解释为状态代码。所以从技术上讲,你可以逃脱:
res.send(404);
Edit:My bad, I meant res
instead of req
. It should be called on the response
编辑:我的错,我的意思是res
而不是req
. 应该在响应中调用它
Edit:As of Express 4, the send(status)
method has been deprecated. If you're using Express 4 or later, use: res.sendStatus(404)
instead. (Thanks @badcc for the tip in the comments)
编辑:从 Express 4 开始,该send(status)
方法已被弃用。如果您使用的是 Express 4 或更高版本,请改用:res.sendStatus(404)
。(感谢@badcc 在评论中提供提示)
回答by craniumonempty
According to the site I'll post below, it's all how you set up your server. One example they show is this:
根据我将在下面发布的站点,这就是您设置服务器的所有方式。他们展示的一个例子是这样的:
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;
and their route function:
以及它们的路由功能:
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;
This is one way. http://www.nodebeginner.org/
这是一种方式。 http://www.nodebeginner.org/
From another site, they create a page and then load it. This might be more of what you're looking for.
他们从另一个站点创建一个页面,然后加载它。这可能是您正在寻找的更多内容。
fs.readFile('www/404.html', function(error2, data) {
response.writeHead(404, {'content-type': 'text/html'});
response.end(data);
});
回答by alessioalex
From the Express site, define a NotFound exception and throw it whenever you want to have a 404 page OR redirect to /404 in the below case:
从Express 站点,定义一个 NotFound 异常并在您想要 404 页面时抛出它或在以下情况下重定向到 /404:
function NotFound(msg){
this.name = 'NotFound';
Error.call(this, msg);
Error.captureStackTrace(this, arguments.callee);
}
NotFound.prototype.__proto__ = Error.prototype;
app.get('/404', function(req, res){
throw new NotFound;
});
app.get('/500', function(req, res){
throw new Error('keyboard cat!');
});
回答by Sam
IMO the nicest way is to use the next()
function:
IMO 最好的方法是使用该next()
函数:
router.get('/', function(req, res, next) {
var err = new Error('Not found');
err.status = 404;
return next(err);
}
Then the error is handled by your error handler and you can style the error nicely using HTML.
然后错误由您的错误处理程序处理,您可以使用 HTML 很好地设置错误样式。