In Express.js, should I return response or not?
It depends.
Calling the res
or req
callback doesn't mean your routing function is gonna stop working
app.get('/url', (req, res) => {
if (true) {
res.send(200, { message: 'ok' });
}
const newFunction = () => {
// stuff useless to your routing function
}
newFunction()
});
In here the newFunction()
is gonna get called and it's useless, it's gonna impact your server performances.
you better use return res.send(200, { message: 'ok' });
everytime, except if you wanna make a process in the background...
A process typically that can't be expected more than the classical 30 seconds http request. (Me I am making one that takes 4 or 5 hours everyday for example :D)
I do not agree with the answer above. Sometimes the callback function can return several responses depending on the logic of the app:
router.post("/url", function(req, res) {
// (logic1)
res.send(200, { response: 'response 1' });
// (logic2)
res.send(200, { message: 'response 2' });
}})
This will throw this error:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
Which can actually be solved with using return. It can also be solved with using if else clauses.
You don't. The (req, res)
signature tells express this is the last function in the chain, and it does not expect a return value from this function. You can add a return statement, but it won't "do anything", beyond the JS engine performing some additional (but meaningless) overhead.