Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get response header via cross-domain ajax?

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.

like image 692
shabunc Avatar asked May 24 '11 15:05

shabunc


People also ask

What does get response header does in AJAX?

getResponseHeader() The XMLHttpRequest method getResponseHeader() returns the string containing the text of a particular header's value.

Does AJAX support cross domain?

For a successful cross-domain communication, we need to use dataType “jsonp” in jquery ajax call. JSONP or “JSON with padding” is a complement to the base JSON data format which provides a method to request data from a server in a different domain, something prohibited by typical web browsers.

How do I make a cross domain AJAX request?

One approach to making cross domain AJAX request is to use a proxy. In this scenario, your script calls an endpoint on your Web application server that is hosting your script and application.

Can we set response header?

You can set response headers, you can add response headers And you can wonder what the difference is. But think about it for a second, then do this exercise. Draw a line from the HttpResponse method to the method's behavior.


1 Answers

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

like image 72
monsur Avatar answered Oct 31 '22 08:10

monsur