如何在 angularjs 中读取响应头?

IT技术 javascript angularjs angular-http
2021-03-12 09:09:11

我的服务器返回这种标题Content-Range:0-10/0::

在此处输入图片说明

我试图以角度阅读这个标题,但没有运气:

var promise = $http.get(url, {
    params: query
}).then(function(response) {
  console.log(response.headers());
  return response.data;
});

只是打印

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

任何想法如何访问内容范围标题?

6个回答

headers在成功和错误回调中使用变量

从文档

$http.get('/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.
  });

如果您在同一个域中,您应该能够检索回响应标头。如果跨域,则需要Access-Control-Expose-Headers在服务器上添加标头。

Access-Control-Expose-Headers: content-type, cache, ...
成功调用似乎已被弃用,不应使用。检查文档:docs.angularjs.org/api/ng/service/$http
2021-04-17 09:09:11
这仍然没有给我响应头,只是请求头。
2021-04-21 09:09:11
是的,默认情况下 CORS 会返回某些标头。并且您需要告诉它哪些其他标头可以安全地通过 api 公开。看到这个
2021-04-30 09:09:11
我已经启用了跨域。我的问题中的屏幕截图显示内容范围标头位于 chrome 检查器的响应内。所以服务器不是问题。
2021-05-03 09:09:11
这不再起作用了!请参阅:stackoverflow.com/questions/41169385/...
2021-05-08 09:09:11

为什么不简单地试试这个:

var promise = $http.get(url, {
    params: query
}).then(function(response) {
  console.log('Content-Range: ' + response.headers('Content-Range'));
  return response.data;
});

特别是如果你想返回promise那么它可能是Promise链的一部分。

您可能不应该在这样的单个请求中使用 A‌ 授权。使用拦截器进行授权
2021-04-15 09:09:11
是跨域请求吗?
2021-04-21 09:09:11
给出 (+1) 是因为response有一个headers()接受name参数方法不过,这是我的问题;即使我可以一目了然地看到我也无法通过以下方式检索Authorization标题 [或任何其他] !!!那么这个函数的世界是什么???response.headers('Authorization')response.config.headers['Authorization']
2021-04-22 09:09:11
Authorization是一个常见的请求头。我从未将其视为响应标头。你确定它真的在你的回复中吗?response.config.headers可能是指该请求,不响应。
2021-04-23 09:09:11
@EugeneRetunsky:我有跨域请求。我可以在响应中看到授权标头,但现在能够获取它。无论如何,我可以这样做,因为 API 正在返回令牌以进行成功的身份验证。
2021-05-10 09:09:11

根据穆罕默德的回答更新......

$http.get('/someUrl').
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
    console.log(headers()['Content-Range']);
  })
  .error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

除了 Eugene Retunsky 的回答之外,还引用了有关响应的$http文档:

响应对象具有以下属性:

  • data{string|Object}– 使用转换函数转换的响应主体。

  • status{number}– 响应的 HTTP 状态代码。

  • headers{function([headerName])}– 标题获取函数。

  • config{Object}– 用于生成请求的配置对象。

  • statusText{string}– 响应的 HTTP 状态文本。

请注意,$resource (v1.6)的参数回调顺序上述不同:

使用(value (Object|Array), responseHeaders (Function), status (number), statusText (string))参数调用成功回调,其中值是填充的资源实例或集合对象。使用(httpResponse)参数调用错误回调

response.headers();

会给你所有的标题(默认和海关)。为我工作!!

在此处输入图片说明

在此处输入图片说明

注意我只在同一个域上测试过。我们可能需要Access-Control-Expose-Headers在服务器上为跨域添加标头。