如何在node / express中发送自定义http状态消息? [英] How to send a custom http status message in node / express?
问题描述
我的node.js应用程序的建模类似于 express / examples / mvc 一个>应用程序
My node.js app is modeled like the express/examples/mvc app.
在控制器操作中,我想使用自定义http消息吐出HTTP 400状态。
默认情况下,http状态消息为不正确请求:
In a controller action I want to spit out a HTTP 400 status with a custom http message. By default the http status message is "Bad Request":
HTTP/1.1 400 Bad Request
但是我想发送
HTTP/1.1 400 Current password does not match
我尝试过各种方式,但没有一个将http状态消息设置为我的自定义消息。
I tried various ways but none of them set the http status message to my custom message.
我目前的解决方案控制器功能如下所示:
My current solution controller function looks like that:
exports.check = function( req, res) {
if( req.param( 'val')!=='testme') {
res.writeHead( 400, 'Current password does not match', {'content-type' : 'text/plain'});
res.end( 'Current value does not match');
return;
}
// ...
}
好,但似乎不是正确的做法。
Everything works fine but ... it seems not the the right way to do it.
有没有更好的方法来设置http状态消息使用express?
Is there any better way to set the http status message using express ?
推荐答案
您可以检查这个 res.send(400,当前密码不匹配)
请查看表达3.x文档详细信息
You can check this res.send(400, 'Current password does not match')
Look express 3.x docs for details
Expressjs 4.x的更新
a href =http://expressjs.com/api.html#res.send =noreferrer> express 4.x docs ):
Use this way (look express 4.x docs):
res.status(400).send('Current password does not match');
// or
res.status(400);
res.send('Current password does not match');
这篇关于如何在node / express中发送自定义http状态消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!