我有以下代码,试图在此使用来自Mongo DB的凭据来验证用户:
{
validate: async function (email, password, res) {
console.log('Inside validate method');
try {
var dbUserObj = await User.findOne({ email: email }, (err, user) => {
console.log('Inside validate method111111');
if (err) {
return res.status(500).send('Error on the server.');
}
console.log('Inside validate method 22222');
if (!user) {
return res.status(404).send('No user found.');
}
console.log('Inside validate method33333');
var passwordIsValid = bcrypt.compareSync(password, user.password);
console.log('Is Valid Password :: ' + passwordIsValid);
if (!passwordIsValid) {
return res.status(401).send({
auth: false,
token: null
});
}
});
} catch (e) {
}
console.log('DDDDBBBB USSSERRRR :::' + dbUserObj);
return dbUserObj;
}
}
以下代码调用validate方法:
var auth = {
login: function(req, res,next) {
console.log('Inside login');
var email = req.body.email || '';
var password=req.body.password || '';
console.log('Before validate user');
// Fire a query to your DB and check if the credentials are valid
var dbUserObj = auth.validate(email,password,res);
if (!dbUserObj) { // If authentication fails, we send a 401 back
res.status(401);
res.json({
"status": 401,
"message": "Invalid credentials"
});
return;
}
if (dbUserObj) {
res.send(genToken(dbUserObj));
}
}
只要出现密码不正确的情况,我就会收到错误消息:
错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置
无法真正找出问题所在。
答案 0 :(得分:1)
调用validate()
的路由需要从express接受the next
callback parameter,否则框架假定异步函数返回时(发生在第一个await
表达式上),它具有完成所有工作,然后继续沿其默认路由进行处理,该错误处理将在您的数据库查询恢复validate
中的异步控制流之前发送404。
当路由处理程序接受next
参数时,它表示要表示路由将异步处理,并且您可以执行以下3种操作之一:
next()
。next()
。next(error)
。中间件将为您处理错误报告和响应。