【问题标题】:Can't read response data and headers in an AngularJS interceptor无法读取 AngularJS 拦截器中的响应数据和标头
【发布时间】:2025-12-03 12:35:01
【问题描述】:

我的服务器中有一个 API,用于发送响应 http://localhost:8081/my/test/api 的自定义标头(我们将其命名为“customHeader”)。

我正在尝试从 angularJS 中的拦截器中读取自定义响应标头:

angular.module('oauth.interceptor', []).factory('readResponseHeader', ['$q',
        function ($q) {
            return {
                response': function(response) {
                    console.log("response: %o", JSON.stringify(response));
                    console.log("headers: %o", response.headers());
                    return response;
                }
            }
        }
    ]);

但我得到的只是空数据和响应头。控制台日志将以下 json 显示为 response

{
  "data": [],
  "status": 200,
  "config": {
    "method": "POST",
    "transformRequest": [
      null
    ],
    "transformResponse": [
      null
    ],
    "url": "http://localhost:8081/my/test/api",
    "data": {
      "example": "request data"
    },
    "headers": {
      "Accept": "application/json, text/plain, */*",
      "Content-Type": "application/json;charset=utf-8",
      "Authorization": "Bearer XXXXXXXXX..."
    },
    "cached": false
  },
  "statusText": "OK"
}

以下作为headers

{
  "content-type": "application/json; charset=UTF-8"
}

我希望我的customHeader 在那里,并且能够通过以下方式阅读它:

response.headers().customHeader

但它显然不存在(事实上,许多其他标题都丢失了!)。 我应该怎么读?

【问题讨论】:

    标签: angularjs angular-http-interceptors


    【解决方案1】:

    我终于发现问题实际上不在 AngularJS 部分,而在服务器端部分。

    关键是,为了能够访问标头,服务器必须添加包含自定义标头名称的 Access-Control-Expose-Headers 标头,如下所示:

    Access-Control-Expose-Headers: customHeader
    

    【讨论】: