当我单击“重置密码”按钮时,它引发的用户未在后端的命令提示符中定义。我在Node.js Express中使用Mongoose。这是模型和控制器的代码。
控制器
const User = require('../models/userModels');
const passwordResetToken = require('../models/resettokenModels');
async ResetPassword(req, res) {
if (!req.body.email) {
return res
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.json({ message: 'Email is required' });
}
const userEmail = await User.findOne({
email: Helpers.lowerCase(req.body.email)
});
if (!userEmail) {
return res
.status(HttpStatus.CONFLICT)
.json({ message: 'Email does not exist' });
}
var resettoken = new passwordResetToken({ _userId: user._id, resettoken: crypto.randomBytes(16).toString('hex') });
resettoken.save(function (err) {
if (err) { return res.status(500).send({ msg: err.message }); }
var transporter = nodemailer.createTransport({
service: '"SendGrid"',
auth:
{
user: 'email',
pass: 'password'
}
});
var mailOptions = {
from: 'email',
subject: 'Node.js Password Reset',
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://' + req.headers.host + '/reset/' + resettoken + '\n\n' +
'If you did not request this, please ignore this email and your password will remain unchanged.\n'
}
transporter.sendMail(mailOptions
)
})
.catch(err => {
res
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.json({ message: 'Error occured' });
});
},
这是模型
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const resettokenSchema = new mongoose.Schema({
_userId: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' },
resettoken: { type: String, required: true },
createdAt: { type: Date, required: true, default: Date.now, expires: 43200 },
});
module.exports = mongoose.model('passwordResetToken', resettokenSchema);
用户模型
const userSchema = new mongoose.Schema({
username: { type: String },
email: { type: String },
password: { type: String },
...
...
控制器内的这一行显示错误
var resettoken = new passwordResetToken({ _userId: user._id, resettoken: crypto.randomBytes(16).toString('hex') });
什么会导致此类问题?
答案 0 :(得分:1)
如评论中所述,您没有将用户设置为任何内容。
编辑:
这是使用您的用户架构的,上面显示了该用户架构的用户名,电子邮件,密码等。
const user = await User.findOne({
email: Helpers.lowerCase(req.body.email)
});
您的重置令牌需要执行以下操作:
var resettoken = new passwordResetToken({ _userId: user._id, resettoken: crypto.randomBytes(16).toString('hex') });
您的nodemailer需要这样做:
var mailOptions = {
from: 'mail@mail.com',
to: user.email,
subject: 'Node.js Password Reset',
text: 'some message'
}
transporter.sendMail(mailOptions)