简体   繁体   中英

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?

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 don't "do anything", beyond the JS engine performing some additional (but meaningless) overhead.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM