Proper way to set response status and JSON content in a REST API made with nodejs and express

dukable picture dukable · Sep 26, 2014 · Viewed 295.6k times · Source

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.

Answer

Michał Dudak picture Michał Dudak · Sep 26, 2014

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:(" });