在发布路线上使用 nodemailer 发送电子邮件并使用 passport.authenticate 将用户保存到 mongodb
Posted
技术标签:
【中文标题】在发布路线上使用 nodemailer 发送电子邮件并使用 passport.authenticate 将用户保存到 mongodb【英文标题】:On post route send email with nodemailer and save user to mongodb with passport.authenticate 【发布时间】:2017-11-28 19:04:30 【问题描述】:我正在尝试在用户使用 nodemailer 注册后发送欢迎电子邮件,并在同一发布路线上使用 passport.authenticate 将用户添加到 mongodb。我可以让它单独工作,即发送电子邮件或将用户添加到数据库,但似乎无法让它们一起工作。我是 nodejs 的新手,非常感谢任何帮助。这是我要上班的路线:
router.post('/signup', function(req, res,next)
async.waterfall([
function(done)
passport.authenticate('signup',
successRedirect: '/',
failureRedirect: '/signup',
failureFlash : true
);
,
function(user, done)
var transporter = nodeMailer.createTransport(
service: 'SendGrid',
auth:
user: 'user',
pass: 'password'
);
var mailOptions =
to: user.email,
from: 'me@gmail.com',
subject: 'Welcome to the site',
html: '<p> This is html, did I render correctly?</p>'
;
transporter.sendMail(mailOptions, function(err)
done(err);
);
], function(err)
res.redirect('/signup');
);
);
这是使用护照的注册策略:
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/user');
var bCrypt = require('bcrypt-nodejs');
module.exports = function(passport)
passport.use('signup', new LocalStrategy(
usernameField : 'email',
passReqToCallback : true
,
function(req, email, password, done)
findOrCreateUser = function()
// find a user in Mongo with provided username
User.findOne( 'email' : email , function(err, user)
// In case of any error, return using the done method
if (err)
req.flash('error','Email Already Exists',err.message);
return done(err);
// already exists
if (user)
console.log('User already exists with username:');
return done(null, false, req.flash('error','Email Already Exists'));
else
// if there is no user with that email
// create the user
var newUser = new User();
// set the user's local credentials
newUser.password = createHash(password);
newUser.email = req.param('email');
newUser.firstName = req.param('firstName');
newUser.lastName = req.param('lastName');
// save the user
newUser.save(function(err)
if (err)
console.log('Error in Saving user: '+err);
return done(null, false, req.flash('error',err.message));
console.log('User Registration succesful');
return done(null, newUser);
);
);
;
// Delay the execution of findOrCreateUser and execute the method
// in the next tick of the event loop
process.nextTick(findOrCreateUser);
)
);
// Generates hash using bCrypt
var createHash = function(password)
return bCrypt.hashSync(password, bCrypt.genSaltSync(10), null);
提前感谢您的帮助!
【问题讨论】:
【参考方案1】:为什么不将电子邮件发送逻辑移至护照注册策略?
【讨论】:
成功了!猜猜我试图通过将其添加到路线来使其过于复杂。我只是把用户成功保存后的email逻辑放到了signup.js文件中,谢谢!以上是关于在发布路线上使用 nodemailer 发送电子邮件并使用 passport.authenticate 将用户保存到 mongodb的主要内容,如果未能解决你的问题,请参考以下文章
带有 Gmail 服务的 Nodemailer 无法在 heroku 上运行