Proper way to set response status and JSON content

2019-01-16 10:43发布

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?

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

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

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?

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

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.

6条回答
forever°为你锁心
2楼-- · 2019-01-16 11:13

I am using this in my Express.js application:

app.get('/', function (req, res) {
    res.status(200).json({
        message: 'Welcome to the project-name api'
    });
});
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-01-16 11:17

Express API reference covers this case.

See status and send.

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

res.status(500).send({ error: "boo:(" });
查看更多
SAY GOODBYE
4楼-- · 2019-01-16 11:18

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.

查看更多
Animai°情兽
5楼-- · 2019-01-16 11:18
res.status(500).jsonp(dataRes);
查看更多
我只想做你的唯一
6楼-- · 2019-01-16 11:19

status of 200 will be the default when using res.send, res.json, etc.

You can set the status like 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.0 http://expressjs.com/4x/api.html#res.sendStatus

查看更多
放我归山
7楼-- · 2019-01-16 11:21

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 and the payload itself) and a 3rd property explaining the error in a human-understandable way in the case of an error.

Stripe's API behaves similarly in the real world.

i.e.

OK

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

Error

400, {status: 400, data: null, message: "You must send foo and bar to baz..."}
查看更多
登录 后发表回答