AJAX CORS – How to Get Response Header via Cross-Domain AJAX

ajaxcorscross-domainhttp-headers

I'm trying to read documentation and I must confess it is not an easy reading. I have no problem (after adding Access-Control-Allow-Origin header) to read responseText, but fail to get response header anywhere except Firefox.

So, my question is what is the right way to get response header, using cross-domain ajax?

I've tried to use (Access-Control-Expose-Headers), but, again, failed to read header.

Best Answer

So the way it should work is that you specify the headers you want the client to have access to in the Access-Control-Expose-Headers header. For example, if your server sets a Foo response header, and you want the client to be able to read it, your server should also send the following header:

Access-Control-Expose-Headers: Foo

On the client side, you can read all the response headers by calling xhr.getAllResponseHeaders(). This returns the response headers as a string, which you can then parse into an object using the following code: https://gist.github.com/706839

That is an explanation of how things should work. However, note that there is a bug in older browsers where the response headers can't be read on the client. See here for more details: CORS xmlhttprequest HEAD method

Related Question