我正在使用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对象是重要的。 我是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.sendStatus(status)已在4.9.0版本中添加

你可以使用这些res.sendStatus() || res.status()方法之一

下面是res.sendStatus() || res.status()之间的差异


res.sendStatus(200) // equivalent to res.status(200).send('OK')
res.sendStatus(403) // equivalent to res.status(403).send('Forbidden')
res.sendStatus(404) // equivalent to res.status(404).send('Not Found')
res.sendStatus(500) // equivalent to res.status(500).send('Internal Server Error')

我希望有人觉得这有帮助 谢谢

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对象是重要的。 我是nodejs的新手,一开始并没有意识到res.json()不仅仅是设置响应的主体。它实际上也试图推断响应状态。所以,如果像这样做:

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

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

获取完整HttpResponse的标准方法,包括以下属性

Body //包含您的数据 头 好吧 状态 statusText 类型 url

在后端,这样做

router.post('/signup', (req, res, next) => {
    // res object have its own statusMessage property so utilize this
    res.statusText = 'Your have signed-up succesfully'
    return res.status(200).send('You are doing a great job')
})

在Frontend中,例如在Angular中,只需执行:

let url = `http://example.com/signup`
this.http.post(url, { profile: data }, {
    observe: 'response' // remember to add this, you'll get pure HttpResponse
}).subscribe(response => {
    console.log(response)
})