Javascript 跨域资源共享 GET:“拒绝从响应中获取不安全的标头“etag””

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5822985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:04:11  来源:igfitidea点击:

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

javascriptajaxweb-applicationsrestcors

提问by Mohamed

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.

一个没有自定义标头的简单 GET 请求。响应按预期返回。可以访问正文中的数据,但不能访问标题。

When I try to access the "etag" header, browsers raise an exception :

当我尝试访问“etag”标头时,浏览器会引发异常:

Refused to get unsafe header "etag"

拒绝获取不安全的标头“etag”

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

Chrome、Safari 和 Firefox 的行为都相同。我没有在 IE 上测试它。

What am I missing here?

我在这里缺少什么?

回答by monsur

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

使用 CORS 时只公开简单的响应头。此处定义简单的响应标头。 ETag不是简单的响应头。如果要公开非简单标头,则需要设置Access-Control-Expose-Headers标头,如下所示:

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.

但是,请注意,我注意到 Chrome、Safari 和 Firefox 中的错误会阻止非简单标头正确公开。这可能现在已经解决了,我不确定。

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

您不需要执行预检请求,因为只有非 GET/POST http 方法或非简单请求标头(并且您正在询问响应标头)才需要预检。

回答by DarkMantis

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

你有没有试过 AJAX 2.0(跨域共享)是 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

还有另一种方法,称为 JSON-P,它类似于 JSON 请求,但您可以将其用于跨域: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

[PS] 不确定这是否有帮助:http: //www.w3.org/Protocols/rfc2616/rfc2616-sec14.html