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

前端 未结 2 798
旧时难觅i
旧时难觅i 2021-02-05 15:36

In our Angular app, we need to parse response headers of some $http.

In particular we need to parse some X-prefixed response headers, for example X-Total-Results:

相关标签:
2条回答
  • 2021-02-05 16:08

    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.

    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

    0 讨论(0)
  • 2021-02-05 16:19

    Use $httpProvider.interceptors you can intercept both the request as well as the response

    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'));
            // ...
        })
    
    0 讨论(0)
提交回复
热议问题