使用< script crossorigin ='anonymous'&gt ;,为什么脚本“被CORS策略阻止”? [英] With <script crossorigin='anonymous'>, why is a script "blocked by CORS policy"?

查看:367
本文介绍了使用< script crossorigin ='anonymous'&gt ;,为什么脚本“被CORS策略阻止”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Google Chrome或Firefox,如果我尝试加载以下HTML:

 < script crossorigin ='anonymous' SRC =HTTPS://stackoverflow.com/foo.js'>< /脚本> 

我得到这样的CORS错误:

< blockquote>

从原点访问 https://stackoverflow.com/foo.js 脚本' https://stackoverflow.com '已被CORS策略阻止:请求中没有'Access-Control-Allow-Origin'标头资源...

然而,没有 crossorigin ='anonymous'属性工作正常(当然会产生一个404错误,因为foo.js不存在)。



这很令人惊讶,因为 anonymous 只是应该阻止发送任何凭据 a>和脚本标记不应该重新QUARE CORS 。是什么导致了这种情况,我应该怎么办?

解决方案

我有一段时间对此感到困惑。以下是我现在了解它的方式:

crossorigin 属性实际上有三个可能的值: anonymous use-credentials ,以及只能通过忽略该属性才能访问的缺省值缺省值。 (另一方面,一个空字符串映射到 anonymous 。)默认值导致浏览器完全跳过CORS,这是我期望的正常行为。



> crossorigin 属性只应用于我们关心获取正在加载的脚本的错误信息。由于访问这些信息需要CORS检查,因此资源上必须存在 Access-Control-Allow-Origin 标题。


With Google Chrome or Firefox, if I try to load the following HTML:

<script crossorigin='anonymous' src='https://stackoverflow.com/foo.js'></script>

I get a CORS error like this:

Access to Script at 'https://stackoverflow.com/foo.js' from origin 'https://stackoverflow.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource...

However, the same tag without the crossorigin='anonymous' attribute works fine (of course generating a 404 error, since foo.js does not exist).

This is surprising, since anonymous is just supposed to prevent sending any credentials, and script tags are not supposed to require CORS. What is causing this, and what should I do?

解决方案

I was confused about this for a while. Here's how I now understand it:

According to the W3C, there are actually three possible values for the crossorigin attribute: anonymous, use-credentials, and an "missing value default" that can only be accessed by omitting the attribute. (An empty string, on the other hand, maps to anonymous.) The default value causes the browser to skip CORS entirely, which is the normal behavior I was expecting.

The crossorigin attribute should only be used if we care about getting error information for the script being loaded. Since accessing this information requires a CORS check, the Access-Control-Allow-Origin header must be present on the resource for it to be loaded.

这篇关于使用&lt; script crossorigin ='anonymous'&gt ;,为什么脚本“被CORS策略阻止”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆