Kevin Kevin - 2 months ago 6
Node.js Question

How to send a message from node.js function to angular controller

I have a variable called

message
in node.js function now I want to send it to angular controller. How to do this?

api.js



router.post('/pages/auth/forgot-password', function(req,res,next){
var maillist = req.body.email;
async.waterfall([
function(done) {
crypto.randomBytes(20, function(err, buf) {
var token = buf.toString('hex');
done(err, token);
});
},

function(token, done) {
User.findOne({ email : maillist}, function(err, user) {
if (!user){
return done(null, false,{message: 'No account with that email address exists.'});
return res.redirect('/pages/auth/forgot-password');
}

user.resetPasswordToken = token;
user.resetPasswordExpires = Date.now() + 3600000;

user.save(function(err) {
done(err, token, user);
});

});
},

function(token, user, done) {
var mailOptions={
to : maillist,
subject : 'Password Recovery',
text: 'You are receiving this because you (or someone else) have requested the reset of the password for your account.\n\n' +
'Please click on the following link, or paste this into your browser to complete the process:\n\n' +
'http://192.127.0.1:3000/pages/auth/reset-password/' + token + '\n\n' +
'If you did not request this, please ignore this email and your password will remain unchanged.\n'
};
transport.sendMail(mailOptions, function(error, response){
if(error){
return done(null, false,{message: 'An e-mail has been sent to ' + maillist + ' with further instructions.'});
}
transport.close();
});

}
], function(err){
if (err) return next(err);
res.redirect('/pages/auth/forgot-password');
});
return res.json({result:message});
});


I am trying to send like
return res.json({result:message});
But it shows an error called
message undefined
.

Answer

Try to do in your last callback

transport.sendMail(mailOptions, function(error, response) {
        if (!error) {
          var message = {
            message: 'An e-mail has been sent to ' + maillist + ' with further instructions.'
          };
          done(null, message);
        }
        transport.close();
      });

And in final callback

  ], function(err,result) {
    if (err) return next(err);
    return res.json({
      result: result.message
    });
  });
Comments