我在使用$ resource时遇到在AngularJS中处理错误响应的麻烦。我的设置可以完美地处理状态200的响应,但是当API抛出400错误时,我只会得到一个空对象。
这是我的 Controller :
$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'} },
}
),
}
}
这是400错误后console.log(error)打印出来的内容:
Object {data: null, status: -1, config: Object, statusText: ""}
最后,这是我没有得到的错误响应API:
{
"errors": {
"message": [
"The town field is required.",
"The postcode field is required.",
]
}
}
任何帮助,将不胜感激,谢谢!
编辑:作为示例,尝试将POST请求发送到https://api.twitter.com/1.1/statuses/destroy/1.json。如果我在 postman 上执行此操作,则会收到以下错误消息:
{
"errors": [
{
"code": 215,
"message": "Bad Authentication data."
}
]
}
如何获得此响应和字符串“身份验证数据错误”。在角?由于某些原因,我无法使用当前设置进行此操作。
最佳答案
该问题可能与您的API服务器和CORS之间的交互有关。
我正在运行一个基于Flask的API后端,该后端也出现了同样的问题。故障排除使我发现在10个连接中的9个中接收到POST请求时,我的API正在执行TCP RST。
Wireshark capture
Flask服务器正在记录响应已正确发送回。
2018-08-19 13:26:59,104 INFO: 127.0.0.1 - - [19/Aug/2018 13:26:59] "POST /users/test HTTP/1.1" 419]
原因
造成此问题的原因是拒绝了API后端中的POST请求,而没有先读取POST数据。我将API重构为始终读取POST数据,从而解决了该问题。
我不清楚CORS如何影响这种情况,但是只有通过Angular而不是直接调用API时才看到此问题。
以下StackOverflow问题向我指出了解决此问题的正确方向。
No response with POST request and Content-Type "application/json" in flask
关于angularjs - Angular资源未返回错误响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38724283/