我有一个项目,我在前端使用Node / Express作为API和Angular。
我有一个端点,我想返回多个字段来填充错误消息。
这是我目前的.post代码:
router.route('/')
.post(function(req, res) {
User.findOne({
login: req.body.login
}, function(err, user) {
if (err)
res.send(err);
if (!user) {
res.send({success: false, msg: 'Authentication failed. User not found.'});
} else {
console.log('User' + user.confirmed)
// check if password matches
user.comparePassword(req.body.password, function (err, isMatch) {
if (isMatch && !err) {
if(user.confirmed){
// if user is found and password is right create a token
var token = jwt.encode(user, config.secret);
// return the information including token as JSON
res.json({success: true, token: 'JWT ' + token});
} else {
res.json({success: false, msg: 'In order to login, you must first confirm you email. A confirmation email was sent to ' + user.email })
}
} else {
res.send({success: false, msg: 'Authentication failed. Wrong password.'});
}
});
}
});
});
关于“success:false”我想返回错误消息标题和错误消息,然后我将在Angular中显示。
我尝试使用“res.json”以及“res.send”。
我在回复中添加了一个“标题”字段,如下所示:
res.json({success: false, title:'Email confirmation needed', msg: 'In order to login, you must first confirm you email. A confirmation email was sent to ' + user.email })
}
但是当我尝试使用“err.title”和“err.msg”在角度方面访问它时,它是未定义的。
这是我的角度控制器:
.controller('LoginController', function($scope, $rootScope, $state, localStorageService, SweetAlert, AuthService){
$scope.user = {
name: '',
password: ''
};
$scope.login = function() {
AuthService.login($scope.user).then(function(msg) {
$state.go('dashboard');
}, function(err) {
console.log('There was an error:', err);
SweetAlert.swal({
title: 'Login Error',
text: err,
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Retry',
closeOnConfirm: true
}, function() { $state.go('login'); });
});
};
});
任何帮助都将不胜感激!!