如何解决“资源需要启用 CORS 的请求...资源已被阻止,因为无法强制执行完整性”错误

How to solve “resource requires the request to be CORS enabled… resource has been blocked because the integrity cannot be enforced” error

我在我的项目中使用 bootstrap 图标,但出现错误

Subresource Integrity: The resource 'http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css' has an integrity attribute, but the resource requires the request to be CORS enabled to check the integrity, and it is not. The resource has been blocked because the integrity cannot be enforced.

任何人都可以帮助我解决这个问题,当我们转向生产时图标没有加载。

所以我使用下面的 link 作为 bootstrap 图标

%link{:href => "http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css", :integrity => "sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7", :rel => "stylesheet"}/

我想你不见了crossorigin="anonymous"

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

When the request doesn't match Same Origin Policy the crossorigin attribute MUST be present for the integrity of the file to be checked. With an integrity set on an external origin and a missing crossorigin the browser will choose to 'fail-open' which means it will load the resource as if the integrity attribute was not set.

Source

我试图通过 Chrome DevTools 控制台将 jQuery 插入到页面中,但出现此错误。这是我使用的代码:

// Bad code
let script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-3.2.1.min.js';
script.crossorigin = 'anonymous';
script.integrity = 'sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=';
document.head.appendChild(script);

解决方案是将 crossorigin 更改为 crossOrigin(Origin 的大写 O):

// Good code
let script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-3.2.1.min.js';
script.crossOrigin = 'anonymous';
script.integrity = 'sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=';
document.head.appendChild(script);