14

I am using the following code for an AJAX call

 $.ajax({
        type: "POST",
        url: "http://******/cxf/view/*****",
        data: {*****},
        headers: {*****},
        success: function (dt, status, request) {
            console.log(request.getAllResponseHeaders());

        },
        error: function (jqXHR, status) {

        }
    });

This is printing only content-type. In the developer console i can see number of headers in the response. How can i get those headers in AJAX

enter image description here

Anoop LL
  • 1,548
  • 2
  • 21
  • 32

3 Answers3

15

It's seems no problem. I tried and got it works.

Use JSONPlaceholder and here is my code

$.ajax({
  url: root + '/posts/1',
  headers: {'test': 'test'},
  method: 'GET'
}).then(function(data, status, xhr) {
  console.log(xhr.getAllResponseHeaders());
});

the result is

Pragma: no-cache
Date: Wed, 23 Dec 2015 06:36:57 GMT
Via: 1.1 vegur
X-Content-Type-Options: nosniff
Server: Cowboy
X-Powered-By: Express
Vary: Origin
Content-Type: application/json; charset=utf-8
Cache-Control: no-cache
Access-Control-Allow-Credentials: true
Content-Length: 292
Etag: W/"124-yv65LoT2uMHrpn06wNpAcQ"
Expires: -1
gaowhen
  • 409
  • 3
  • 7
8

On your server you need to add

res.header("Access-Control-Expose-Headers", "header-you-want-to-expose");

and then you will be able to access it in the browser.

user1071182
  • 1,609
  • 3
  • 20
  • 28
  • @ZachSmith Perhaps the downvoter took offence to the presumed server technology (node?), although in this case it can be easily transferred to any other - so it's not appropriate in my opinion. – John Apr 29 '17 at 22:05
  • Adding this header is the answer. Although OP doesn't specifally state it is a cross origin request, it is implied by the CORS headers shown in their screenshot. +1 from me. – Dave Kennard Dec 09 '17 at 11:56
5

I used the same code you used

success: function (dt, status, request) {
            console.log(request.getAllResponseHeaders());

Problem is not with Jquery or Ajax. Response headers are set by Server. The server you are sending the request to, is not setting the headers! Simple!!!!

When i tried with my server [Some responses blurred for security] i got the following output

Snap of Console output

Arjun
  • 3,248
  • 18
  • 35
  • The how the developer console shows those headers ?? – Anoop LL Dec 23 '15 at 06:52
  • @AnoopLL You should set headers of a response when returning a response. If its OK can you show me the code of cfx/view ?? – Arjun Dec 23 '15 at 07:05
  • I have added an Image in my question. Actually we are using rest call and its cross domain. You can see response headers in that image, those headers are set from the server. – Anoop LL Dec 23 '15 at 07:11