我正在使用Nodejs和通过构建一个小的rest API来表达。我的问题是,设置代码状态以及响应数据的良好实践/最佳方法是什么?

让我用一小段代码来解释(我不会放启动服务器所需的节点和表达代码,只放相关的路由器方法):

router.get('/users/:id', function(req, res, next) {
  var user = users.getUserById(req.params.id);
  res.json(user);
});


exports.getUserById = function(id) {
  for (var i = 0; i < users.length; i++) {
    if (users[i].id == id) return users[i];
  }
};

下面的代码工作完美,当发送一个请求与邮差,我得到以下结果:

如您所见,状态显示为200,这是正常的。但这是最好的方法吗?是否有一种情况下,我应该设置自己的状态,以及返回的JSON?还是特快专递?

例如,我只是做了一个快速测试,并稍微修改了上面的get方法:

router.get('/users/:id', function(req, res, next) {
  var user = users.getUserById(req.params.id);
  if (user == null || user == 'undefined') {
    res.status(404);
  }
  res.json(user);
});

如您所见,如果在数组中没有找到用户,我将只设置404状态。

更多关于这个主题的资源/建议是非常欢迎的。


当前回答

发送错误响应的最佳方式是返回res.status(400)。发送({消息:'错误已发生'})。

然后,在你的前端,你可以用这样的东西来捕捉它:

        url: your_url,
        method: 'POST',
        headers: headers,
        data: JSON.stringify(body),
    })
        .then((res) => {
            console.log('success', res);
        })
        .catch((err) => {
            err.response && err.response.data && this.setState({ apiResponse: err.response.data })
        })

仅仅记录err将不起作用,因为您发送的消息对象驻留在err.response.data中。

希望有帮助!

其他回答

我没有看到任何人提到的事实,方法调用的顺序对res对象是重要的。 我是nodejs的新手,一开始并没有意识到res.json()不仅仅是设置响应的主体。它实际上也试图推断响应状态。所以,如果像这样做:

res.json({"message": "Bad parameters"})
res.status(400)

第二行是没有用的,因为基于正确构建的json, express/nodejs已经推断出了成功状态(200)。

我在我的Express.js应用程序中使用这个:

app.get('/', function (req, res) {
    res.status(200).json({
        message: 'Welcome to the project-name api'
    });
});

你可以这样做:

res.status(400).json(json_response);

这将把HTTP状态代码设置为400,即使在express 4中也能工作。

HTTP状态码列表

The good-practice regarding status response is to, predictably, send the proper HTTP status code depending on the error (4xx for client errors, 5xx for server errors), regarding the actual JSON response there's no "bible" but a good idea could be to send (again) the status and data as 2 different properties of the root object in a successful response (this way you are giving the client the chance to capture the status from the HTTP headers and the payload itself) and a 3rd property explaining the error in a human-understandable way in the case of an error.

Stripe的API在现实世界中的行为类似。

i.e.

OK

200, {status: 200, data: [...]}

错误

400, {status: 400, data: null, message: "You must send foo and bar to baz..."}
res.status(500).jsonp(dataRes);