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
You could do this
return res.status(201).json({
statusCode: req.statusCode,
method: req.method,
message: 'Question has been added'
});
res.status(500).jsonp(dataRes);
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
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..."}
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:(" });
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'
});
});