如何读取angularjs中的响应头?

Upv*_*ote 31 javascript angularjs angular-http

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

在此输入图像描述

我试着用角度读这个标题而没有运气:

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

只打印

Object {content-type: "application/json; charset=utf-8"}
Run Code Online (Sandbox Code Playgroud)

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

Muh*_*eda 38

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.
  });
Run Code Online (Sandbox Code Playgroud)

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

Access-Control-Expose-Headers: content-type, cache, ...
Run Code Online (Sandbox Code Playgroud)

  • 成功调用似乎已被弃用,不应使用.检查文档:https://docs.angularjs.org/api/ng/service/$http (7认同)
  • 这不再起作用了!见:/sf/ask/2881856981/ (2认同)

Eug*_*sky 31

为什么不试试这个:

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

特别是如果你想要返回,promise那么它可能是承诺链的一部分.

  • 给(+)因为`response`有一个`headers()`方法,它接受一个`name`参数.这是我的问题; 我无法通过`response.headers('Authorization')检索`Authorization`标题[或任何其他标题],即使我能看到`response.config.headers ['Authorization']`!世界上这个功能是什么呢? (2认同)
  • `Authorization` 是一个常见的 _request_ 标头。我从未将其视为响应标头。你确定这确实在你的回复中吗?`response.config.headers` 可能指的是请求,而不是响应。 (2认同)

med*_*oix 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.
  });
Run Code Online (Sandbox Code Playgroud)


Wto*_*wer 7

除了Eugene Retunsky的回答,引用$ http文档关于回复:

响应对象具有以下属性:

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

  • status - {number}- 响应的HTTP状态代码.

  • 标题 - {function([headerName])}- 标题getter函数.

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

  • statusText - {string}- 响应的HTTP状态文本.

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

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