0

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

Community
  • 1
  • 1
Vibhas
  • 241
  • 5
  • 20
  • Use return anywhere you want to stop further middle-ware execution! And there is no need to call it after res.send(), just 'return res.send()' would work! – Ali Sep 05 '16 at 11:33

1 Answers1

2

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'});
}
Raj Adroit
  • 3,828
  • 5
  • 31
  • 44
Wai Yan
  • 582
  • 9
  • 22
  • So is it right if I specify return after each and every json response that I send to client because res.json eventually calls res.send but setting content-type. – Vibhas Sep 05 '16 at 09:22
  • Correct. But you don't need to add return everywhere. For example, in your current code, you don't need to add return after res.json() in 'if - else' because nothing is executed afterwards. – Wai Yan Sep 05 '16 at 09:26