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
req and res won't fire any more events, but the code in your callbacks is free to continue running (so long as it does not attempt to call methods on res that require a valid response to be open). this answer was very helpful and has convinced me to leave nodejs for ideological reasons.
But what if we want to send some data and end the response? The answer is simple, res. send() (and remember, res. json() ) both allow us to send some data and they also end the response, so there's no need to explicitly call res.
json() Function. The res. json() function sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using the JSON.
res. send() or res. json() should end all writing to the response stream and send the response. However, you absolutely can call next() if you want to do further processing after the response is sent, just make sure you don't write to the response stream after you call res.
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.
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