In Express.js why does code after res.json() still execute?

davidx1 picture davidx1 · May 19, 2016 · Viewed 8k times · Source

In Node with Express, I have a piece of code like this.

 if (req.body.var1 >= req.body.var2){
        res.json({success: false, message: "End time must be AFTER start time"});
        console.log('Hi')
 }
 console.log('Hi2')
 //other codes

I expected that if var1 is >= var2, the response would be sent and the execution would end. Like return statements in Java/C#

But appearantly that's not the case. After the response is sent, both 'Hi' and 'Hi2' and all the other code after that continues to get executed.

I was wondering how I would stop this from happening?

Also, I was wondering under what circumstances would you actually want code to keep on executing after a response has already been sent.

Cheers

Answer

Thank you picture Thank you · May 19, 2016

Express just calls a JavaScript function for the matched route. There's no special magic to know when the function is complete/incomplete. It just runs the function. However, it's very easy to exit the function whenever you want...

You can use return to stop executing the callback for a specific route in express. It's just JavaScript... the function will always attempt to run to completion

app.post('/some/route', (req, res)=> {
  if (req.body.var1 >= req.body.var2){
    // note the use of `return` here
    return res.json({success: false, message: "End time must be AFTER start time"});
    // this line will never get called
    console.log('Hi')
  }
  // this code will only happen if the condition above is false
  console.log('Hi2')
  //other codes
});

Warning about string comparsion

You're using

req.body.var1 >= req.body.var2

All HTML form values are sent to the server as strings.

// javascript string comparison
"4" > "3"  //=> true
"4" > "30" //=> true
parseInt("4", 10) > parseInt("30", 10) //=> false

I'm certain you'll need to make a more educated comparison than that. It looks like they're time values? So you'll likely want to convert those values to Date objects and do an accurate comparison.