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

前端 未结 12 752
无人及你
无人及你 2020-11-30 20:25

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

12条回答
  •  悲哀的现实
    2020-11-30 20:46

    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

提交回复
热议问题