node.js 如何在节点/快递中发送自定义http状态消息?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14154337/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:52:40  来源:igfitidea点击:

How to send a custom http status message in node / express?

node.jsexpress

提问by lgersman

My node.js app is modeled like the express/examples/mvcapp.

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

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 消息吐出 HTTP 400 状态。默认情况下,http 状态消息是“Bad Request”:

HTTP/1.1 400 Bad Request

But I want to send

但我想发送

HTTP/1.1 400 Current password does not match

I tried various ways but none of them set the http status message to my custom message.

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

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.

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

Is there any better way to set the http status message using express ?

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

回答by mamacdon

None of the existing answers accomplish what the OP originally asked for, which is to override the default Reason-Phrase(the text appearing immediately after the status code) sent by Express.

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

What you want is res.statusMessage. This is not part of Express, it's a property of the underlying http.Response object in Node.js 0.11+.

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

You can use it like this (tested in Express 4.x):

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

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

Then use curlto verify that it works:

然后使用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

回答by Peter Gerasimenko

You can check this res.send(400, 'Current password does not match')Look express 3.x docsfor details

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

UPDATE for Expressjs 4.x

Expressjs 4.x 的更新

Use this way (look express 4.x docs):

使用这种方式(看express 4.x docs):

res.status(400).send('Current password does not match');
// or
res.status(400);
res.send('Current password does not match');

回答by vineet

At server side(Express middleware):

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

if(err) return res.status(500).end('User already exists.');

Handle at Client side

在客户端处理

Angular:-

角度:-

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

jQuery:-

jQuery:-

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

回答by Manoj Ojha

You can use it like this

你可以像这样使用它

return res.status(400).json({'error':'User already exists.'});

回答by hunterloftis

One elegant way to handle custom errors like this in express is:

在 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);
}

(you can also use express' built-in express.errorHandlerfor this)

(您也可以为此使用 express 的内置express.errorHandler

Then in your middleware, before your routes:

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

app.use(errorHandler);

Then where you want to create the error 'Current password does not match':

那么你想在哪里创建错误“当前密码不匹配”:

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);
}

回答by Sharadh

My use-case is sending a custom JSON error message, since I'm using express to power my REST API. I think this is a fairly common scenario, so will focus on that in my answer.

我的用例发送自定义 JSON 错误消息,因为我使用 express 来支持我的 REST API。我认为这是一个相当普遍的情况,因此将在我的回答中重点讨论。

Short Version:

精简版:

Express Error Handling

快速错误处理

Define error-handling middleware like other middleware, except with four arguments instead of three, specifically with the signature (err, req, res, next). ... You define error-handling middleware last, after other app.use() and routes calls

像其他中间件一样定义错误处理中间件,除了使用四个参数而不是三个参数,特别是使用签名(err、req、res、next)。... 在其他 app.use() 和路由调用之后,您最后定义错误处理中间件

app.use(function(err, req, res, next) {
    if (err instanceof JSONError) {
      res.status(err.status).json({
        status: err.status,
        message: err.message
      });
    } else {
      next(err);
    }
  });

Raise errors from any point in the code by doing:

通过执行以下操作从代码中的任何一点引发错误:

var JSONError = require('./JSONError');
var err = new JSONError(404, 'Uh oh! Can't find something');
next(err);

Long Version

长版

The canonical way of throwing errors is:

抛出错误的规范方式是:

var err = new Error("Uh oh! Can't find something");
err.status = 404;
next(err)

By default, Express handles this by neatly packaging it as a HTTP Response with code 404, and body consisting of the message string appended with a stack trace.

默认情况下,Express 通过将其巧妙地打包为代码为 404 的 HTTP 响应来处理此问题,正文由附加了堆栈跟踪的消息字符串组成。

This doesn't work for me when I'm using Express as a REST server, for example. I'll want the error to be sent back as JSON, not as HTML. I'll also definitely not want my stack trace moving out to my client.

例如,当我使用 Express 作为 REST 服务器时,这对我不起作用。我希望将错误作为 JSON 而不是 HTML 发回。我也绝对不希望我的堆栈跟踪移到我的客户端。

I can send JSON as a response using req.json(), eg. something like req.json({ status: 404, message: 'Uh oh! Can't find something'}). Optionally, I can set the status code using req.status(). Combining the two:

我可以使用 JSON 作为响应发送req.json(),例如。类似的东西req.json({ status: 404, message: 'Uh oh! Can't find something'})。或者,我可以使用req.status(). 两者结合:

req.status(404).json({ status: 404, message: 'Uh oh! Can't find something'});

This works like a charm. That said, I find it quite unwieldy to type every time I have an error, and the code is no longer self-documenting like our next(err)was. It looks far too similar to how a normal (i.e, valid) response JSON is sent. Further, any errors thrown by the canonical approach still result in HTML output.

这就像一个魅力。也就是说,我发现每次出现错误时都很难输入,而且代码不再像我们next(err)以前那样具有自我记录功能。它看起来与普通(即有效)响应 JSON 的发送方式非常相似。此外,规范方法抛出的任何错误仍会导致 HTML 输出。

This is where Express' error handling middleware comes in. As part of my routes, I define:

这就是 Express 的错误处理中间件的用武之地。作为我的路由的一部分,我定义了:

app.use(function(err, req, res, next) {
    console.log('Someone tried to throw an error response');
  });

I also subclass Error into a custom JSONError class:

我还将 Error 子类化为自定义 JSONError 类:

JSONError = function (status, message) {
    Error.prototype.constructor.call(this, status + ': ' + message);
    this.status = status;
    this.message = message;
  };
JSONError.prototype = Object.create(Error);
JSONError.prototype.constructor = JSONError;

Now, when I want to throw an Error in the code, I do:

现在,当我想在代码中抛出错误时,我会这样做:

var err = new JSONError(404, 'Uh oh! Can't find something');
next(err);

Going back to the custom error handling middleware, I modify it to:

回到自定义错误处理中间件,我将其修改为:

app.use(function(err, req, res, next) {
  if (err instanceof JSONError) {
    res.status(err.status).json({
      status: err.status,
      message: err.message
    });
  } else {
    next(err);
  }
}

Subclassing Error into JSONError is important, as I suspect Express does an instanceof Errorcheck on the first parameter passed to a next()to determine if a normal handler or an error handler must be invoked. I can remove the instanceof JSONErrorcheck and make minor modifications to ensure unexpected errors (such as a crash) also return a JSON response.

将 Error 子类化为 JSONError 很重要,因为我怀疑 Express 会instanceof Error检查传递给 a 的第一个参数,next()以确定是否必须调用普通处理程序或错误处理程序。我可以删除instanceof JSONError检查并进行小的修改以确保意外错误(例如崩溃)也返回 JSON 响应。

回答by Ted Bigham

If your goal is just to reduce it to a single/simple line, you could rely on defaults a bit...

如果您的目标只是将其简化为单行/简单行,则可以稍微依赖默认值...

return res.end(res.writeHead(400, 'Current password does not match'));

回答by KNDheeraj

Well in the case of Restify we should use sendRaw()method

那么在 Restify 的情况下,我们应该使用sendRaw()方法

Syntax is: res.sendRaw(200, 'Operation was Successful', <some Header Data> or null)

语法是: res.sendRaw(200, 'Operation was Successful', <some Header Data> or null)