下面是我的/authenticate 方法的一部分,它找到具有给定 username
和 password
的用户。
User.findOne({
username: req.body.username,
password: req.body.password
}, function(err, user) {
if (err) {
res.json({
type: false,
"status": "401",
"data": "Incorrect email/password"
});
} else {
if (user) {
console.log("token");
res.json(generateToken(user));
} else {
res.json({
type: false,
"status": "401",
"data": "Incorrect email/password"
});
}
}
});
当没有这样的username
或password
时,if(err)
中的条件永远不会触发。
其次,当我从我的 angular-js 代码调用此方法时,无论 success/error
只调用成功。
login: function (username, password) {
return $http.post('http://localhost:8888/login', {
username: username,
password: password
});
}
我的 Controller 调用代码:
AutheService.login(username, password).success(function(response) {
console.log(response); // error message as well as success comes here
}).error(function(data, status){
console.log(data, status);
})
最佳答案
您需要在服务器端以实际错误代码作为响应。我假设您正在使用 expressJS 并且在查看了他们的文档之后,您可以将您的响应链接起来,例如 res.status(401).json(...)
:
User.findOne({
username: req.body.username,
password: req.body.password
}, function(err, user) {
if (err) {
res.status(401).json({
type: false,
"status": "401",
"data": "Incorrect email/password"
});
} else {
if (user) {
console.log("token");
res.json(generateToken(user));
} else {
res.status(401).json({
type: false,
"status": "401",
"data": "Incorrect email/password"
});
}
}
});
关于javascript - 仅调用成功处理程序 - AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32215720/