Javascript 正在尝试验证节点js中的令牌
用户注册后,我会向他们发送一封包含令牌和电子邮件地址的链接的电子邮件。当他们单击该链接时,我试图通过从url查询字符串获取令牌对象和电子邮件值,然后在我的数据库中查找匹配的令牌来验证令牌。然而,即使令牌变量存储在外部函数中,我也会一直为它获取空值(当我在内部函数中使用它时)Javascript 正在尝试验证节点js中的令牌,javascript,node.js,express,mongoose,Javascript,Node.js,Express,Mongoose,用户注册后,我会向他们发送一封包含令牌和电子邮件地址的链接的电子邮件。当他们单击该链接时,我试图通过从url查询字符串获取令牌对象和电子邮件值,然后在我的数据库中查找匹配的令牌来验证令牌。然而,即使令牌变量存储在外部函数中,我也会一直为它获取空值(当我在内部函数中使用它时) //------------------------------------------------- TOKEN VERIIFICATION ----------------------------------------
//------------------------------------------------- TOKEN VERIIFICATION ------------------------------------------------
function verifyToken(req, res)
{
var email = req.query.email
var token = req.query.token
Token.findOne({ token: token },
function (err, token) {
console.log(token)
if (!token || token === undefined)
res.render('verify', { notif: 'We were unable to find a valid token. Your token may have expired.' });
// If we found a token, find a matching user
console.log("token was found")
User.findOne({ _id: token._userId, email: email }, function (err,) {
if (!user) res.render('verify', { notif: 'We were unable to find a user for this token.' });
if (user.isVerified) res.render('verify', { notif: 'This user has already been verified.' });
// Verify and save the user
user.isVerified = true;
user.save(function (err) {
if (err) { res.render('verify', { notif: err.message }); }
res.render('verify', { notif: 'The account has been verified. Please log in.' });
});
});
});
}
// ------------------------------------------------- END OF TOKEN VERIFICATION ---------------------------------------------
exports.registerUser = registerUser
我在我的server.js中调用上述函数,如下所示:
app.get('/verify', function (req, res) {
userController.verifyToken(req, res);
//res.render('verify', { title: "Email Verification" });
})
我成功地获取了email和token值,然后将它们存储在变量中,但当我尝试在token.findOne的相应函数中访问它们时,它们为NULL。请帮帮我
编辑*
这是我的令牌的模式
const tokenSchema = new mongoose.Schema({
_userId: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' },
token: { type: String, required: true },
createdAt: { type: Date, required: true, default: Date.now, expires: 43200 }
});
这是它在数据库中的外观:
{ "_id" : ObjectId("5f640985f6dcb40988328a57"), "_userId" : ObjectId("5f640985f6dcb40988328a56"), "token" : "487f7b22f68312d2c1bbc93b1aea445b", "createdAt" : ISODate("2020-09-18T01:12:37.339Z"), "__v" : 0 }
同时
现在当我设置Token.findOne({Token:Token})时
我得到了这个错误:TypeError:无法读取null属性“\u userId”我发现了错误 令牌模型未注册为架构,因为我正在使用:
const tokenSchema = new mongoose.Schema
尽管我已经使用以下方法定义了“模式”:
var Schema = mongoose.Schema
因此,通过以下方式解决了问题:
const tokenSchema = new Schema
token
在数据库中不存在。如果定义了token=req.query.token
,则它确实存在于数据库中,但来自.findOne()
回调的token
表示您查询的内容不存在。如果是这种情况,请在用户签名显示您的证据后,再次检查您的匹配令牌是否正确保存在您的db中,或者打印我们的err
,而不是token
确定我刚刚检查了我的数据库,令牌是否正确保存