Reputation: 4915
Is it necessary to respond with a status 200
code or is it the default behavior?
response.json({
status: 'OK',
});
vs.
response
.status(200)
.json({
status: 'OK',
});
When I hit the route in my browser, I get a 200 response in both cases
By now, I only use status code for other responses than 200 (e.g. 404, 500)
Upvotes: 12
Views: 5157
Reputation: 31973
The Express response object wraps the underlying Node.js response object. In Node.js, if you don't set a response, it will always be 200
. Express operates the same way for most requests. It will also automatically handle setting some error response codes for you depending on if and where an error was thrown.
Further, Express will set the response code for you on certain types of routes, for example, if you've defined a redirect, it will automatically set the 302
code for you.
Upvotes: 16