如何使用Express.js指定HTTP错误代码? [英] How to specify HTTP error code using Express.js?
本文介绍了如何使用Express.js指定HTTP错误代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试过:
app.get('/',function(req,res,next){var e = new Error('错误消息');e.状态= 400;下一个(e);});
和:
app.get('/',function(req,res,next){res.statusCode = 400;var e = new Error('错误消息');下一个(e);});
,但始终会声明错误代码500.
解决方案
根据Express(版本4以上)文档,您可以使用:
res.status(400);res.send('没有人可以通过');
http://expressjs.com/4x/api.html#res.status >
< = 3.8
res.statusCode = 401;res.send('没有人可以通过');
I have tried:
app.get('/', function(req, res, next) {
var e = new Error('error message');
e.status = 400;
next(e);
});
and:
app.get('/', function(req, res, next) {
res.statusCode = 400;
var e = new Error('error message');
next(e);
});
but always an error code of 500 is announced.
解决方案
Per the Express (Version 4+) docs, you can use:
res.status(400);
res.send('None shall pass');
http://expressjs.com/4x/api.html#res.status
<=3.8
res.statusCode = 401;
res.send('None shall pass');
这篇关于如何使用Express.js指定HTTP错误代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文