我正在使用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状态。

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


当前回答

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(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中。

希望有帮助!

快速API参考涵盖了这种情况。

查看状态并发送。

简而言之,你只需要在调用json或send之前调用status方法:

res.status(500).send({ error: "boo:(" });

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..."}

你可以这样做

            return res.status(201).json({
                statusCode: req.statusCode,
                method: req.method,
                message: 'Question has been added'
            });
try {
  var data = {foo: "bar"};
  res.json(JSON.stringify(data));
}
catch (e) {
  res.status(500).json(JSON.stringify(e));
}