只有成功处理程序被称为 – AngularJS

以下是我的/ authenticate方法的一部分,它find一个给定usernamepassword

  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" }); } } }); 

当没有这样的usernamepasswordif(err)从不发生,

其次,当我从我的angular-js代码调用这个方法时,不pipesuccess/error失败,只有成功被调用。

 login: function (username, password) { return $http.post('http://localhost:8888/login', { username: username, password: password }); } 

我的控制器调用代码:

 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" }); } } });