我正在记下服务器,在登录方法中它中断了,告诉我在发送标头后无法设置标头。但是目的只是返回一个json。谢谢。
这是我的代码,我正在使用bcrypt来设置更安全的用户密码。
function login(req,res,next){
if(req.headers.email && req.headers.password){
if(req.headers.email.indexOf('@')>=0 || req.headers.password.length>0){
var emailz = req.headers.email;
var passwordz = req.headers.password;
user.findOne({email:emailz}).then(result=>{
console.log(result);
if(!result){
return res.status(401).send({error:'userDoesNotExists'});
}
bcrypt.compare(passwordz,result.password,function(err,same){
if(!same){
return res.status(401).send({error:'PasswordIsNotCorrect'});
}
var utente = {id: result.id, username:result.username, email:result.email, name:result.name, surname:result.surname};
console.log('Token',jwt.encode(utente,config.TOKEN_SECRET,'HS256'));
next();
return res.status(200).redirect('/');
})
})
}
}
return res.status(401).send({error:'EmailOrPasswordAreEmpty'});
}
答案 0 :(得分:0)
user.findOne
最有可能进行数据库查找,因此是异步的。无论if语句内部发生什么,您的最低回报都会触发。在最后一个返回值旁边加上另一个。
function login(req,res,next){
if(req.headers.email && req.headers.password){
if(req.headers.email.indexOf('@')>=0 || req.headers.password.length>0){
var emailz = req.headers.email;
var passwordz = req.headers.password;
user.findOne({email:emailz}).then(result=>{
console.log(result);
if(!result){
return res.status(401).send({error:'userDoesNotExists'});
}
bcrypt.compare(passwordz,result.password,function(err,same){
if(!same){
return res.status(401).send({error:'PasswordIsNotCorrect'});
}
var utente = {id: result.id, username:result.username, email:result.email, name:result.name, surname:result.surname};
console.log('Token',jwt.encode(utente,config.TOKEN_SECRET,'HS256'));
next();
return res.status(200).redirect('/');
})
})
}
} else {
return res.status(401).send({error:'EmailOrPasswordAreEmpty'});
}
}