首页 > 解决方案 > 加载本地 css 和 js 文件时出现 Cors 错误

问题描述

当使用脚本和链接标签加载 js/css 文件(来自 vue 项目)时,浏览器拒绝加载它们。这些是错误:

Access to script at 'http://www.example.com/js/app.7f934f5b.js' from origin 'http://example.com' has been blocked by CORS policy: 
No 'Access-Control-Allow-Origin' header is present on the requested resource.

此错误发生在 iOS 和 macOS 上的最新 Safari 以及最新的 Chrome 开发人员版本中。

由于标签是由 生成的yarn build,它使用 vue cli 构建生产版本,我无法控制标签的生成方式。

下面是带有 content-security-policy 元标记的 index.html。

<!DOCTYPE html>
<html lang="en">
<head>
    <base href="<%= BASE_URL %>">
    <meta http-equiv="Content-Security-Policy" content="default-src self; script-src self 'unsafe-inline' 'unsafe-eval' http: https:; style-src self 'unsafe-inline' http: https:; img-src self data: http: https:; font-src self http: https:; connect-src http: https: ws:">
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width,initial-scale=1.0"/>
    <link rel="icon" href="<%= BASE_URL %>favicon.ico"/>
    <link href="fontawesome/css/all.css" rel="stylesheet"/>
    <title>Application title</title>
</head>
<body>
<noscript>
    <strong>
        We're sorry but Vue.js doesn't work properly without JavaScript enabled.
        Please enable it to continue.
    </strong>
</noscript>
<div id="app">
</div>
</body>
</html>

如果有人对如何解决此问题有任何建议,请告诉我!

标签: javascripthtmlcsscorscontent-security-policy

解决方案


www.example.comexample.com一样的出身

为避免此问题,请选择一个规范并将所有其他请求重定向到它。


推荐阅读