简体   繁体   English

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

[英]Response header is present in browser but not parsed by Angular $http response.headers()

In our Angular app, we need to parse response headers of some $http. 在我们的Angular应用程序中,我们需要解析一些$ http的响应头。

In particular we need to parse some X-prefixed response headers, for example X-Total-Results: 35 . 特别是我们需要解析一些X-prefixed响应头,例如X-Total-Results: 35

Opening the Network tab of the browser dev tools and inspecting the resource relative to the $http request, I verified that the response header X-Total-Results: 35 is present. 打开浏览器开发工具的Network选项卡并检查相对于$ http请求的资源,我验证了响应头X-Total-Results: 35存在。

in the browser, the X-Total-Results header is available, but cannot be parsed in the Angular $http. 在浏览器中,X-Total-Results标头可用,但无法在Angular $ http中解析。

Is there a way to access in $http the 'raw' response and write our custom parser for the header? 有没有办法在$ http中访问'raw'响应并为头文件编写自定义解析器?

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

console output 控制台输出

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

results header: null

The reason you can't read the header on JavaScript but you can view it on the developer console is because for CORS requests, you need to allow the client to read the header. 您无法在JavaScript上读取标题但您可以在开发人员控制台上查看它的原因是因为对于CORS请求,您需要允许客户端读取标头。

Your server needs to send this header: 您的服务器需要发送此标头:

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

To answer your question in the comments, The Access-Control-Allow-Headers does not allow wildcards according to the W3 Spec 要在评论中回答您的问题, Access-Control-Allow-Headers不允许根据W3规范使用通配符

Use $httpProvider.interceptors you can intercept both the request as well as the response 使用$ httpProvider.interceptors可以拦截请求和响应

for example 例如

$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);
                 },
             };
         }]);

Update : You can retrive your headers info in call itself 更新:您可以在通话中检索标题信息

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM