2015-03-02 199 views
26

我的服务器返回的这种标题的:Content-Range:0-10/0如何在angularjs中读取响应头?

enter image description here

我试过的角度看这个头,没有运气:

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"} 

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

回答

30

使用的成功和错误回调

From documentationheaders变量。

$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, ... 
+0

这仍然没有给我响应头,只是请求头。 – 2015-03-02 08:48:56

+0

更新了答案。 – 2015-03-02 08:52:16

+0

我已经启用跨网域。我的问题中的屏幕截图显示,内容范围标题位于chrome检查器中的响应中。所以服务器不是问题。 – 2015-03-02 08:57:14

9

基于穆罕默德的答案更新中...

$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. 
    }); 
22

为什么不干脆试试这个:

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

特别是如果你想要回promise所以它可能是一部分一个承诺链。

+2

给出一个(+1),因为'response'有一个'headers'参数的'headers()'方法。虽然这是我的问题;我无法通过'response.headers('Authorization')'检索'Authorization'头文件[或任何其他文件],即使我可以在明显的地方看到response.config.headers ['Authorization']!这个功能是什么,然后呢? – Cody 2016-06-10 04:12:50

+0

这是一个跨域请求吗? – 2016-06-13 21:02:13

+0

你可能不应该在这样的单个请求中使用A uthorization。使用拦截器授权的东西 – 2016-08-16 08:20:56

5

此外尤金Retunsky的答案,从关于响应$http文档引用:

响应对象具有以下属性:

  • 数据 - {string|Object} - 响应体与转化转换功能。

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

  • 标头 - {function([headerName])} - 标头吸气功能。

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

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

请注意参数回调整理的$resource(V1。6)是不一样的如上:

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

0

Cors情况下的响应标题保持隐藏状态。 您需要添加回应标题以指示Angular向JavaScript公开标题。

// From server response headers : 
header("Access-Control-Allow-Methods: GET, POST, OPTIONS"); 
header("Access-Control-Allow-Headers: Origin, X-Requested-With, 
Content-Type, Accept, Authorization, X-Custom-header"); 
header("Access-Control-Expose-Headers: X-Custom-header"); 
header("X-Custom-header: $some data"); 

var data = res.headers.get('X-Custom-header'); 

来源:https://github.com/angular/angular/issues/5237