在呼叫$http返回错误消息
Return error message on $http call
在 Angular 中,我发出了一个$http请求,并希望返回一条错误消息,但不确定如何返回。
在 Express 中,我想在出错时执行以下操作(或类似操作)。
res.send(400, { errors: 'blah' });
在 Angular 中,我目前有这个:
$http.post('/' ,{}).then(function(res) { }, function(err) {
console.log(err) // no errors data - only 400 error code
});
如何从 Angular 中访问"错误"(即"等等")?
$http消息提供,成功和错误功能:
$http({method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
如果出现问题,例如服务器错误或其他http错误,错误功能将被触发,您可以捕获错误。
如果其他内容触发或您必须向用户提供某种反馈,则可以使用成功方法,但将数据作为其他圆顶返回,如下所示:
data {message: 'your message here', success: /*true or false*/, result: /*some data*/ }
然后在成功函数中:
$http({method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
if(data.success) {
// do stuff here
}
else {
// show the error or notification somewhere
}
}).
error(function(data, status, headers, config) {
//do stuff if error 400, 500
});
我知道
这是一个老问题,但是..我相信你想要的是:
angular.module('App').factory('MainFactory', function($http) {
return {
post: function(something) {
$http
.post('/api', something)
.then(function(result) {
return result.data;
}, function(err) {
throw err.data.message;
});
}
};
});
并且来自一个控制器
angular.module('App').controller('Ctrl', function($scope, MainFactory ) {
$scope.something_to_send = "something"
MainFactory
.post($scope.something_to_send)
.then(function(result){
// Do something with result data
}, function(err) {
// showError(err);
});
});
相关文章:
- jQuery在输入下验证post错误消息
- 在AngularJs中隐藏默认错误消息
- 如果用户输入的长度小于最小长度,则显示错误消息
- 使用ASP.NET CustomValidator避免重复的错误消息
- KOValidation在错误消息中获取可观察值、$index()、$data等
- 更改精细上载中的错误消息
- 如何在页面刷新时隐藏错误消息
- 如何显示错误消息
- 滑块未显示,控制台中没有错误消息
- 表单提交没有'如果为空,则不会显示错误消息
- 为什么我的Alexa技能测试显示正确的lambda输出,但在开发人员控制台中测试时却给出错误消息
- 隐藏错误消息“;未选择文件”;asp:fileUpload的文本
- 登录时显示自定义错误消息
- 如何仅在存在最小值和最大值时才显示错误消息
- 通过 AJAX 检索 Blob 时处理错误消息
- Javascript 错误:消息:预期的“)”
- 如何将错误消息从 meteor 服务器传递到客户端
- 为什么 Angularjs 总是显示错误消息
- 我如何让我的 var 错误消息输出是使用字段还是字段,具体取决于留空的字段数
- 将错误消息 JSON 传递到另一个页面模板