响应头存在于浏览器中但未由Angular $ http response.headers()解析

时间:2015-09-04 18:04:01

标签: javascript angularjs http http-headers httpresponse

在我们的Angular应用程序中,我们需要解析一些$ http的响应头。

特别是我们需要解析一些带X前缀的响应头,例如X-Total-Results: 35

打开浏览器开发工具的Network标签并检查相对于$ http请求的资源,我确认响应标头X-Total-Results: 35已存在。

在浏览器中,X-Total-Results标头可用,但无法在Angular $ http中解析。

有没有办法在$ http中访问'raw'响应并为标题编写自定义解析器?

$http.({method: 'GET', url: apiUrl,)
    .then( function(response){
        console.log('headers: ', response.headers());
        console.log('results header: ', response.headers('X-Total-Results'));
        // ...
    })

控制台输出

headers: Object {cache-control: "no-cache="set-cookie"", content-type: "application/json;charset=utf-8"}

results header: null

2 个答案:

答案 0 :(得分:23)

您无法在JavaScript上阅读标题,但可以在开发人员控制台上查看它的原因是因为对于CORS请求,您需要允许客户端读取标题。

您的服务器需要发送此标头:

Access-Control-Expose-Headers:X-Total-Results

要在评论中回答您的问题,Access-Control-Allow-Headers根据W3 Spec

不允许使用通配符

答案 1 :(得分:0)

使用$ httpProvider.interceptors可以拦截请求和响应

例如

$httpProvider.interceptors.push(['$q', '$injector', function ($q, $injector) {
             return {
                 'responseError': function (response) {
                     console.log(response.config);
                 },
                 'response': function (response) {
                     console.log(response.config);
                 },
                 'request': function (response) {
                     console.log(response.config);
                 },
             };
         }]);

更新:您可以在通话中重新审核您的标题信息

$http.({method: 'GET', url: apiUrl)
    .then( (data, status, headers, config){
        console.log('headers: ', config.headers);
        console.log('results header: ', config.headers('X-Total-Results'));
        // ...
    })
相关问题