Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read response headers for CORS request with jQuery

I have a working cross-domain web service call where I get my payload back, but I cannot read the headers in the response. Chrome can show me the headers in the request fine, but they are not available in jQuery's success handler.

var data_obj = { "userName": "myUser", "password": "000000" }

$.ajax({
    type: "POST",
    url: 'https://localhost:8443/AuthService.svc/auth',
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify(data_obj),
    dataType: "json",
    success: function(data, textStatus, jqXHR) {
        console.log(jqXHR.getAllResponseHeaders());
    }
});

The only thing that gets logged to the console is:

Content-Type: application/json; charset=utf-8

Here is what Chrome is reporting for the OPTIONS and POST response headers, note that I am attempting to expose Foo and Authorization via Acccess-Control-Expose-Headers:

OPTIONS

Acccess-Control-Expose-Headers:Content-Type, Foo, Authorization
Access-Control-Allow-Headers:Content-Type, Foo, Authorization
Access-Control-Allow-Methods:POST, PUT, DELETE
Access-Control-Allow-Origin:*
Access-Control-Max-Age:1728000
Content-Length:0
Date:Mon, 20 Jul 2015 16:26:00 GMT
Foo:Bar

POST

Acccess-Control-Expose-Headers:Content-Type, Foo, Authorization
Access-Control-Allow-Headers:Content-Type, Foo, Authorization
Access-Control-Allow-Origin:*
Authorization: custom_access_token = some_token
Content-Length:36
Content-Type:application/json; charset=utf-8
Date:Mon, 20 Jul 2015 16:26:00 GMT
Foo:Bar

Can anyone figure out why I can only access the Content-Type header in my success callback?

Update

Note I refactored the above to use XMLHttpRequest, the behaviour persists.

like image 606
Mister Epic Avatar asked Jul 20 '15 16:07

Mister Epic


1 Answers

There is a typo in your response header:

Acccess-Control-Expose-Headers:Content-Type, Foo, Authorization

You have three "c" in "access". I admit it took too long for me to notice too.

While I don't have Chrome (only Firefox), I replicated your request as closely as I could and fixing the typo returned this:

Foo: Bar
Authorization: custom_access_token = some_token
Content-Type: text/html; charset=utf-8

Addendum

Seeing that another answer is advising you to use withCredentials, if for some reason you did that, remember that Access-Control-Allow-Origin must match the Origin request header that your browser will likely set on its own and it can not be a wildcard. I'm putting this here to avoid another possible issue.

The origin parameter specifies a URI that may access the resource. The browser must enforce this. For requests without credentials, the server may specify "*" as a wildcard, thereby allowing any origin to access the resource.

See the Mozilla docs

like image 179
spenibus Avatar answered Oct 06 '22 01:10

spenibus