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

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


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


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.


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.0http://expressjs.com/4x/api.html#res.sendStatus