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)
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)
Share Improve this question edited Dec 26, 2021 at 10:00 marcobiedermann asked Nov 20, 2018 at 23:18 marcobiedermannmarcobiedermann 4,9235 gold badges28 silver badges39 bronze badges 5- I wouldn't say it is necessary, but it certainly is the convention. – Narm Commented Nov 20, 2018 at 23:22
- No, it is not necessary. The former does so without calling .status(200). Why ask if you've already confirmed this? – Kevin B Commented Nov 20, 2018 at 23:26
- 2 I'd say it's more of a best practice kinda thing... Personally... But no, it's not pulsory by any means. – JO3-W3B-D3V Commented Nov 20, 2018 at 23:29
- @KevinB Thank you for your answer. I was asking because I was not sure about my statement and could not find any answer in the express documentation nor somewhere else. Everyone is using it differently and I was looking for a best practice and even if there might be still some benefit from one over the other – marcobiedermann Commented Nov 20, 2018 at 23:30
- it's not at all a "best practice"... it's just a method you can call if you so choose to. it isn't necessary, you can accept the default, or pass a value to ensure it is what you want it to be. – Kevin B Commented Nov 20, 2018 at 23:34
1 Answer
Reset to default 16The 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.