在使用 nodejs 和 express 制作的 REST API 中设置响应状态和 JSON 内容的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26066785/
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
Proper way to set response status and JSON content in a REST API made with nodejs and express
提问by dukable
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?
我正在使用 Nodejs 并通过构建一个小的 rest API 来表达。我的问题是,设置代码状态以及响应数据的最佳实践/最佳方法是什么?
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):
用一点代码解释一下(我不会放启动服务器所需的node和express代码,只放关心的router方法):
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];
}
};
The code below works perfectly, and when sending a request with Postman, I get the following result:

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

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?
可以看到,状态显示为200,正常。但这是最好的方法吗?是否有我必须自己设置状态以及返回的 JSON 的情况?还是总是由快递处理?
For example, I just made a quick test and slightly modified the get method above:
比如我刚刚做了一个快速测试,稍微修改了上面的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);
});
As you can see, if the user is not found in the array, I will just set a status of 404.
如您所见,如果在数组中找不到用户,我将只设置状态为 404。
Resources/advices to learn more about this topic are more than welcome.
非常欢迎提供有关此主题的更多信息的资源/建议。
回答by Micha? Dudak
回答by mzalazar
You could do it this way:
你可以这样做:
res.status(400).json(json_response);
This will set the HTTP status code to 400, it works even in express 4.
这会将 HTTP 状态代码设置为 400,它甚至可以在 express 4 中工作。
回答by Jordonias
status of 200 will be the default when using res.send, res.json, etc.
使用、 等时res.send,状态 200 将是默认值res.json。
You can set the status like res.status(500).json({ error: 'something is wrong' });
您可以将状态设置为 res.status(500).json({ error: 'something is wrong' });
Often I'll do something like...
通常我会做一些像...
router.get('/something', function(req, res, next) {
// Some stuff here
if(err) {
res.status(500);
return next(err);
}
// More stuff here
});
Then have my error middleware send the response, and do anything else I need to do when there is an error.
然后让我的错误中间件发送响应,并在出现错误时做我需要做的任何其他事情。
Additionally: res.sendStatus(status)has been added as of version 4.9.0http://expressjs.com/4x/api.html#res.sendStatus
另外:res.sendStatus(status)已添加到4.9.0版http://expressjs.com/4x/api.html#res.sendStatus
回答by cmlndz
A list of HTTP Status Codes
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 andthe payload itself) and a 3rd property explaining the error in a human-understandable way in the case of an error.
关于状态响应的良好做法是,可以预见,根据错误发送正确的 HTTP 状态代码(客户端错误为 4xx,服务器错误为 5xx),关于实际的 JSON 响应,没有“圣经”,但一个好主意可能是在成功的响应中(再次)将状态和数据作为根对象的 2 个不同属性发送(这样您就可以让客户端有机会从 HTTP 标头和有效负载本身捕获状态)和第三个属性解释在出现错误的情况下,以人类可以理解的方式出错。
Stripe'sAPI behaves similarly in the real world.
Stripe 的API 在现实世界中的行为类似。
i.e.
IE
OK
好的
200, {status: 200, data: [...]}
Error
错误
400, {status: 400, data: null, message: "You must send foo and bar to baz..."}
回答by mrks
I am using this in my Express.js application:
我在 Express.js 应用程序中使用它:
app.get('/', function (req, res) {
res.status(200).json({
message: 'Welcome to the project-name api'
});
});
回答by WasiF
The standard way to get full HttpResponse that includes following properties
获取包含以下属性的完整 HttpResponse 的标准方法
- body //contains your data
- headers
- ok
- status
- statusText
- type
- url
- body //包含你的数据
- 标题
- 好的
- 地位
- 状态文本
- 类型
- 网址
On backend, do this
在后端,执行此操作
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')
})
On Frontende.g. in Angular, just do:
在前端,例如 in 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)
})
回答by Gustavo Grisales
res.status(500).jsonp(dataRes);
回答by Sma Ma
try {
var data = {foo: "bar"};
res.json(JSON.stringify(data));
}
catch (e) {
res.status(500).json(JSON.stringify(e));
}
回答by Prathamesh More
You could do this
你可以这样做
return res.status(201).json({
statusCode: req.statusCode,
method: req.method,
message: 'Question has been added'
});
回答by Radu
The best way of sending an error response would be return res.status(400).send({ message: 'An error has occurred' }).
发送错误响应的最佳方式是return res.status(400).send({ message: 'An error has occurred' }).
Then, in your frontend you can catch it using something like this:
然后,在您的前端,您可以使用以下内容捕获它:
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 })
})
Just logging errwon't work, as your sent message object resides in err.response.data.
仅记录是err行不通的,因为您发送的消息对象驻留在err.response.data.
Hope that helps!
希望有帮助!

