【发布时间】:2016-08-02 15:11:53
【问题描述】:
我在使用 $resource 时遇到了在 AngularJS 中处理错误响应的麻烦。我的设置与状态 200 响应完美配合,但是当 API 抛出 400 错误时,我只得到一个空对象。
这是我的控制器:
$scope.createProduct = function() {
Api.product.save($scope.product).$promise.then(
function(res) {
console.log(res);
},
function(error) {
console.log(error);
}
)
}
这是我的 Api 服务:
function ApiService($resource, API_URL) {
return {
product: $resource(
API_URL + '/product/:product_id', { 'product_id': '@product_id' },
{
show: { method: 'GET' },
update: { method: 'PUT', headers: {'Content-Type': 'application/json'} },
}
),
}
}
这是 console.log(error) 在 400 错误后打印出来的内容:
Object {data: null, status: -1, config: Object, statusText: ""}
最后这是我没有得到的错误响应 API:
{
"errors": {
"message": [
"The town field is required.",
"The postcode field is required.",
]
}
}
任何帮助将不胜感激,谢谢!
编辑:例如,尝试向https://api.twitter.com/1.1/statuses/destroy/1.json 发送 POST 请求。如果我在 Postman 上执行此操作,我会收到以下错误消息:
{
"errors": [
{
"code": 215,
"message": "Bad Authentication data."
}
]
}
如何获得此响应和字符串“错误的身份验证数据”。在角?出于某种原因,我目前的设置无法做到这一点。
【问题讨论】:
-
首先检查你的浏览器控制台,你真的收到来自服务器的json吗?尝试将
headers: {'Accept': 'application/json}添加到您的 api 保存功能。 -
不,我在 Chrome 中收到此请求的“加载响应数据失败”错误,所以我认为我在调用 API 时做错了什么。我确实在 Postman 中得到了正确的错误响应。不幸的是,添加该行并没有帮助。
-
发布你的api url和需要发送的对象
-
这是我在本地运行的私有 API,Sajeetharan,但它只是一个简单的 POST 请求,请求中包含 JSON 正文。
-
save产品服务方法在哪里?
标签: angularjs error-handling resources