目前,我在“Javascript”代码中遇到了承诺问题。它不断抛出“TypeError:res.status(...)。json(...)。catch不是一个函数”,我猜我的承诺在代码行的某处是错误的。
这是我到目前为止所做的:
route.js
route.post('/login', function(req, res) {
log.login(req,res).then((post)=>{
res.status(200).json({message: post})
.catch((error)=>{
res.status(400).json({message: error})
})
})
});
和login.js
function login(req,res){
console.log('here', req.body.email, req.body.password)
if (!req.body.email || !req.body.password) {
return Promise.resolve({success: false, msg: 'Please pass email and password.'});
} else {
return Promise.resolve(User.findOne({
'local.email': req.body.email
})).exec().then((user)=> {
if (!user) {
return Promise.reject({success:false, msg: 'Authentication failed. User not found'}); //res.send({success: false, msg: 'Authentication failed. User not found.'});
} else {
// check if password matches
if(user.validPassword(req.body.password)) {
// if user is found and password is right create a token
var token = jwt.sign(user.id, config.secret);
// return the information including token as JSON
return Promise.resolve({success: true, token: 'JWT ' + token});
} else {
return Promise.reject({success: false, msg: 'Authentication failed. Wrong password.'});
}
}
}).catch((errors)=>{
return ({message: "Could not propose login"});
})
}
}
module.exports = {
login
}
答案 0 :(得分:1)
我相信您错过了})
,固定代码:
route.post('/login', function(req, res) {
log.login(req,res).then((post) => {
res.status(200).json({message: post})
})
.catch((error) => {
res.status(400).json({message: error})
})
})
});