jQuery cross domain request response headers

nLL picture nLL · Feb 28, 2012 · Viewed 15.5k times · Source

I am making cross domain ajax requests with html data type. They work OK as I include

Access-Control-Allow-Origin

in the response from the server. Problem is I need to get certain headers from the server's response and whatever I do, response headers apart from "content type" return null.

jQuery does the request, retrieves the response including headers (I can see it from the traffic) but it doesn't parse it.

I have tried using

crossDomain: true

It didn't help. Here is the sample response from the server.

Access-Control-Allow-Origin:*
Cache-Control:private
Content-Encoding:gzip
Content-Length:514
Content-Type:text/html; charset=utf-8 
X-MYRESPONSEHEADER:1

If requesting and responding document are on same server

 success: function (data, status, xhr) {
        totalRows = xhr.getResponseHeader("X-MYRESPONSEHEADER");

works fine. I have also tried to assign $.ajax to a variable like

var jQxhr = $.ajax(.....

I don't see why it wouldn't be parsed since jQuery actually makes the request and gets the response

Any ideas? Am I missing something?

Update or dragon's comment

Headers sent to request

HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip
Vary: Accept-Encoding
Server: Microsoft-IIS/7.5
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: X-MYRESPONSEHEADER
Access-Control-Allow-Methods: POST
Access-Control-Allow-Methods: GET
X-MYRESPONSEHEADER: 24
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Wed, 29 Feb 2012 11:34:21 GMT

Content-Length: 514

Answer

dragon picture dragon · Feb 28, 2012

You need to add another CORS-specific header in the server response, Access-Control-Allow-Headers. In this case,

Access-Control-Allow-Headers: X-MYRESPONSEHEADER

Ref: https://developer.mozilla.org/en/http_access_control#Access-Control-Allow-Headers