在使用 nodejs 和 express 制作的 REST API 中设置响应状态和 JSON 内容的正确方法 [英] Proper way to set response status and JSON content in a REST API made with nodejs and express

查看:35
本文介绍了在使用 nodejs 和 express 制作的 REST API 中设置响应状态和 JSON 内容的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am playing around with Nodejs and express by building a small rest API. My question is, what is the good practice/best way to set the code status, as well as the response data?

我用一点代码解释一下(我不会放启动服务器所需要的node和express代码,只放关心的router方法):

Let me explain with a little bit of code (I will not put the node and express code necessary to start the server, just the router methods that are concerned):

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

下面的代码完美运行,当使用 Postman 发送请求时,我得到以下结果:

The code below works perfectly, and when sending a request with Postman, I get the following result:

如您所见,状态显示为 200,这是可以的.但这是最好的方法吗?是否有我必须自己设置状态以及返回的 JSON 的情况?还是一直由快递处理?

As you can see, the status shows 200, which is OK. But is this the best way to do this? Is there a case where I should have to set the status myself, as well as the returned JSON? Or is that always handled by express?

比如我刚刚做了一个快速测试,稍微修改了上面的get方法:

For example, I just made a quick test and slightly modified the get method above:

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.

As you can see, if the user is not found in the array, I will just set a status of 404.

非常欢迎提供有关此主题的更多信息的资源/建议.

Resources/advices to learn more about this topic are more than welcome.

推荐答案

Express API 参考涵盖了这种情况.

Express API reference covers this case.

参见状态发送.

简而言之,您只需要在调用jsonsend 之前调用status 方法:

In short, you just have to call the status method before calling json or send:

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

这篇关于在使用 nodejs 和 express 制作的 REST API 中设置响应状态和 JSON 内容的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆