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
Simply return after the
res.json
function: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 completionWarning about string comparsion
You're using
All HTML form values are sent to the server as strings.
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.You can return with
res.json
too.