Reputation: 261
I am using node to create restful api and got confused while sending response.
Below is sample code :
router.post('/', function(req, res) {
var mobileRegex=/^\d{10}$/;
if (!mobileRegex.test(req.body.mobile)){
res.json({status:'success',type:false,msg:'Invalid Mobile'});
// I dont want further execution of code after this but still it continues and prints data not defined
// OR
return res.json({status:'success',type:false,msg:'Invalid Mobile'});
//but works if I specify return before it
}
var data={...};
signupModel.createUser(data,function(err,result){
if(err)
{
res.json({status:'success',type:false,msg:'....'});
}
else
{
res.json({status:'success',type:false,id:'....'});
}
});
When I don't specify return during my failed mobile validation response it continues further execution of code and prints 'data is undefined' in console but Invalid mobile message json is properly send to client without in error trace.
I am confused what is right way to follow when creating api in nodejs my concern is request should not be processed further once response is send. Also if return ends the response should I use return everywhere when I send json response to client in all cases.
I had seen Nodejs difference between 'res.json(..)' and 'return res.json(..)' thread but its concerned with middleware but in my case there is none
Upvotes: 0
Views: 3749
Reputation: 582
You can add a return
statement after res.json()
. res.json()
simply sets the response. It does not send the response.
if (!mobileRegex.test(req.body.mobile)){
return res.json({status:'success', type:false, msg:'Invalid Mobile'});
}
Upvotes: 2