【问题标题】:Angular resource not returning error response角度资源不返回错误响应
【发布时间】: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


【解决方案1】:

该问题可能与您的 API 服务器和 CORS 之间的交互有关。

我正在运行一个基于 Flask 的 API 后端,该后端出现了同样的问题。故障排除使我发现我的 API 在 10 个连接中大约有 9 个接收到 POST 请求时正在执行 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

【讨论】:

    猜你喜欢
    • 2014-11-14
    • 1970-01-01
    • 2017-07-19
    • 2018-11-22
    • 1970-01-01
    • 2019-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多