如何在node/express中发送自定义http状态消息?

lge*_*man 74 node.js express

我的node.js应用程序的建模类似于express/examples/mvc应用程序.

在控制器操作中,我想用自定义http消息吐出HTTP 400状态.默认情况下,http状态消息为"错误请求":

HTTP/1.1 400 Bad Request
Run Code Online (Sandbox Code Playgroud)

但我想发送

HTTP/1.1 400 Current password does not match
Run Code Online (Sandbox Code Playgroud)

我尝试了各种方法,但没有一个将http状态消息设置为我的自定义消息.

我当前的解决方案控制器功能如下所示:

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;
  } 
  // ...
}
Run Code Online (Sandbox Code Playgroud)

一切正常,但......似乎不是正确的方法.

有没有更好的方法来使用快递设置http状态消息?

mam*_*don 76

现有的答案都没有完成OP最初要求的内容,即覆盖Express发送的默认Reason-Phrase(紧接状态代码后出现的文本).

你想要的是什么res.statusMessage.这不是Express的一部分,它是Node.js 0.11+中底层http.Response对象的属性.

您可以像这样使用它(在Express 4.x中测试):

function(req, res) {
    res.statusMessage = "Current password does not match";
    res.status(400).end();
}
Run Code Online (Sandbox Code Playgroud)

然后用curl它来验证它的工作原理:

$ curl -i -s http://localhost:3100/
HTTP/1.1 400 Current password does not match
X-Powered-By: Express
Date: Fri, 08 Apr 2016 19:04:35 GMT
Connection: keep-alive
Content-Length: 0
Run Code Online (Sandbox Code Playgroud)

  • 这是将`statusMessage`设置为映射到StatusCode的标准消息以外的正确方法 (6认同)
  • 您可以使用`res.nativeResponse.statusMessage`获取底层对象中的属性 (4认同)
  • 这应该适用于 HTTP1.1,而不是 HTTP2:https://nodejs.org/dist/latest-v15.x/docs/api/http2.html#http2_response_statusmessage (2认同)

Pet*_*nko 53

您可以查看此res.send(400, 'Current password does not match') Look express 3.x文档以获取详细信息

Expressjs 4.x的更新

使用这种方式(看表达4.x文档):

res.status(400).send('Current password does not match');
// or
res.status(400);
res.send('Current password does not match');
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,这不会设置http状态消息,但会发送'当前密码不匹配'作为正文内容... (37认同)
  • 它有效,但它是在正文中发送的,而不是作为“原因短语”......请参阅下面@mamacdon的答案,这是唯一正确的答案 (3认同)

hun*_*tis 11

在express中处理这样的自定义错误的一种优雅方式是:

function errorHandler(err, req, res, next) {
  var code = err.code;
  var message = err.message;
  res.writeHead(code, message, {'content-type' : 'text/plain'});
  res.end(message);
}
Run Code Online (Sandbox Code Playgroud)

(你也可以使用express'内置express.errorHandler)

然后在您的中间件中,在您的路线之前:

app.use(errorHandler);
Run Code Online (Sandbox Code Playgroud)

然后你想在哪里创建错误'当前密码不匹配':

function checkPassword(req, res, next) {
  // check password, fails:
  var err = new Error('Current password does not match');
  err.code = 400;
  // forward control on to the next registered error handler:
  return next(err);
}
Run Code Online (Sandbox Code Playgroud)


vin*_*eet 9

在服务器端(Express中间件):

if(err) return res.status(500).end('User already exists.');
Run Code Online (Sandbox Code Playgroud)

处理客户端

角度: -

$http().....
.error(function(data, status) {
  console.error('Repos error', status, data);//"Repos error" 500 "User already exists."
});
Run Code Online (Sandbox Code Playgroud)

jQuery的: -

$.ajax({
    type: "post",
    url: url,
    success: function (data, text) {
    },
    error: function (request, status, error) {
        alert(request.responseText);
    }
});
Run Code Online (Sandbox Code Playgroud)


Man*_*jha 6

你可以这样使用

return res.status(400).json({'error':'User already exists.'});
Run Code Online (Sandbox Code Playgroud)

  • 这不是OP所要求的;@mamacdon 是唯一做对的人 (2认同)

小智 6

使用 Axios 时,您可以通过以下方式检索自定义响应消息:

\n
Axios.get(\xe2\x80\x9cyour_url\xe2\x80\x9d)\n.then(data => {\n... do something\n}.catch( err => {\nconsole.log(err.response.data) // you want this\n})\n
Run Code Online (Sandbox Code Playgroud)\n

...在 Express 中将其设置为:

\n
res.status(400).send(\xe2\x80\x9cyour custom message\xe2\x80\x9d)\n
Run Code Online (Sandbox Code Playgroud)\n