我想使用nodeMailer重置密码。
这是我的发帖路线: /routes/api/auth.js
router.post('/user', (req, res) => {
const { email } = req.body
User.findOne({ email })
.then(user => {
if (!user) return res.status(400).json({ msg: 'User does not exist' });
jwt.sign(
{ id: user.id },
config.get('jwtSecret'),
{ expiresIn: 3600 },
(err, token) => {
if (err) throw err;
res.json({
token,
user: {
id: user.id,
name: user.name,
email: user.email
}
});
const url = getPasswordResetURL(user, token);
console.log(url);
transporter.sendMail(resetPasswordTemplate(user, url), (err, info) => {
})
}
)
})
});
和我的功能: /modules/mailModule.js
const nodemailer = require('nodemailer');
const config = require('config');
const transporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: config.get('email'),
pass: config.get('password')
}
})
const getPasswordResetURL = (user, token) =>
`http://localhost:3000/password/reset/${user._id}/${token}`
const resetPasswordTemplate = (user, url) => {
const from = config.get('email')
const to = user.email
const subject = "Password Reset"
const html = `
<p>Hey ${user.name || user.email},</p>
<p>We heard that you lost your password. Sorry about that!</p>
<p>But don’t worry! You can use the following link to reset your password:</p>
<a href=${url}>${url}</a>
<p>If you don’t use this link within 1 hour, it will expire.</p>
`
return { from, to, subject, html }
}
module.exports = { transporter, getPasswordResetURL, resetPasswordTemplate }
和/config/default.json(当然,我删除了此帖子的个人数据)
{
"mongoURI": "atlasClusterLink",
"jwtSecret": "jwtPassword",
"email": "myEmail@gmail.com",
"password": "myPassword"
}
在我完成的第一个文件中
console.log(url)
检查使用url更改密码是否可行,并且可以,但是我无法发送。我什么也没收到。第一次执行此操作时,我收到来自Google无回复邮件(严重安全警报)的消息,提示某人(我)试图通过非Google应用程序登录我的帐户。 我只想在某些邮件地址上发送此url,如果我可以使用无回复邮件地址来完成此操作,那就太好了。 稍后我还计划使用dotenv代替config,但是稍后会实现。