For Express.js 4.x I can't find wether I should return the response (or next function) or not, so:
This:
app.get('/url', (req, res) => {
res.send(200, { message: 'ok' });
});
Or this:
app.get('/url', (req, res) => {
return res.send(200, { message: 'ok' });
});
And what is the difference?
The var app = express() statement creates a new express application for you. The createApplication function from the lib/express. js file is the default export, which we see as the express() function call. The app object returned from this function is one that we use in our application code.
The Response object (res) specifies the HTTP response which is sent by an Express app when it gets an HTTP request.
There is no actual difference between res. send and res.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With