Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Express.js, should I return response or not?

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?

like image 728
Nicky Avatar asked Dec 13 '15 22:12

Nicky


People also ask

What does Express function return?

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.

What is the use of express JS response object?

The Response object (res) specifies the HTTP response which is sent by an Express app when it gets an HTTP request.

Is there any difference between Res send and return Res send in express JS?

There is no actual difference between res. send and res.


1 Answers

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.

like image 170
AG_HIHI Avatar answered Oct 14 '22 03:10

AG_HIHI