Anoop LL
Anoop LL

Reputation: 1575

How to get Response headers in AJAX

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

Upvotes: 14

Views: 28325

Answers (3)

user1071182
user1071182

Reputation: 1627

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.

Upvotes: 9

gaowhen
gaowhen

Reputation: 409

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

Upvotes: 15

Arjun
Arjun

Reputation: 3793

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

Upvotes: 5

Related Questions