Cross Domain Resource Sharing GET: 'refused to get unsafe header "etag"' from Response

JavascriptAjaxWeb ApplicationsRestCors

Javascript Problem Overview


A simple GET request with no custom headers. The response is returned as expected. The data in the body is accessible, but not the headers.

When I try to access the "etag" header, browsers raise an exception : > Refused to get unsafe header "etag"

Chrome, Safari and Firefox all behave the same. I didn't test it on IE.

What am I missing here?

Javascript Solutions


Solution 1 - Javascript

Only simple response headers are exposed when using CORS. Simple response headers are defined here. ETag is not a simple response headers. If you want to expose non-simple headers, you need to set the Access-Control-Expose-Headers header, like so:

Access-Control-Expose-Headers: ETag

However, note that I've noticed bugs in Chrome, Safari and Firefox that prevent non-simple headers from being exposed correctly. This may be fixed by now, I'm not sure.

You shouldn't need to do a preflight request, since preflight is only required for non-GET/POST http methods or non-simple request headers (and you are asking about response headers).

Solution 2 - Javascript

Have you ever tried AJAX 2.0 (Cross domain sharing) is a methodology fairly recently brought out by W3C: http://www.w3.org/TR/XMLHttpRequest2/#ref-cors

Also there is another way of doing this, which is called JSON-P, it's like a JSON request, but you can use it for cross-domains: http://en.wikipedia.org/wiki/JSONP

Both can be very dangerous to the site owners if not setup correctly though. So do be careful when using it.

[PS] Not sure if this will help : http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLocalistView Question on Stackoverflow
Solution 1 - JavascriptmonsurView Answer on Stackoverflow
Solution 2 - JavascriptDarkMantisView Answer on Stackoverflow