Reputation: 1870
I have a simple POST request with sending mail by nodemailer.
app.post("/sendMail", function(req, res) {
nodemailer.sendMail({ from: 'xx', to: userEmail }, function(error, info) {
if (error) {
return res.send(500, 'Internal error, try again later');
}
res.send(200, 'Mail sent!');
});
});
However, for security reasons, Im not storing user mail anywhere in client-side. But in the request, I have user id
.
Single collection in db looks like:
{
id: '1312feew3',
email: '[email protected]',
}
So if my req.body.id
equals to 1312feew3
, I need to get that specified collection and take the email
out from it
I tried to do simple:
var userEmail = getUserById(req.body.id, function (err, user) {
if (err) {
return res.send(400, 'Something went wrong');
}
return res.json(user);
}).email;
(I placed it on the second line in the first code)
Unfortunately it didnt work as I expected.
It doesnt throw any errors, however the mail is not being sent.
Upvotes: 0
Views: 33
Reputation: 311835
Assuming that getUserById
is async, it can't return the user directly and you have to access it from within the callback function:
getUserById(req.body.id, function (err, user) {
if (err) {
return res.send(400, 'Something went wrong');
}
var userEmail = user.email;
// Send the email here, within the callback as well.
...
return res.json(user);
});
Upvotes: 1