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

前端 未结 12 757
无人及你
无人及你 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:39

    res.sendStatus(status) has been added as of version 4.9.0

    you can use one of these res.sendStatus() || res.status() methods

    below is difference in between res.sendStatus() || res.status()

    
    res.sendStatus(200) // equivalent to res.status(200).send('OK')
    res.sendStatus(403) // equivalent to res.status(403).send('Forbidden')
    res.sendStatus(404) // equivalent to res.status(404).send('Not Found')
    res.sendStatus(500) // equivalent to res.status(500).send('Internal Server Error')
    
    

    I hope someone finds this helpful thanks

提交回复
热议问题