javascript - "access to script from origin ' null ' has been blocked by CORS policy"尝试使用导入的 js 函数启动 html 页面时出错

标签 javascript html visual-studio-code import

尝试使用从另一个文件导入函数的 javascript 文件启动 html 页面时出现此错误:

Access to script at 'file:///C:/Users/bla/Desktop/stuff/practice/jsPractice/funcexecute.js' 
from origin 'null' has been blocked by CORS policy: 
Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
Failed to load resource: net::ERR_FAILED

这是html代码:
<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Page Title</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>

</head>
<body>
    <script type = 'module' src='funcexecute.js'></script>

</body>
</html>

从 html 调用的 js 文件:(funcexecute.js)
import sumup from '/funcfile.js';
console.log(sumup(1,2));

导入模块:
(funcfile.js)
function sumup(num1, num2){
    return num1+num2;
}
export default sumup;

我怎样才能解决这个问题? (我使用vscode)

最佳答案

不使用服务器就不能将脚本文件用作模块。
Take a look here

以下是一些选项

  • 使用 Live Server(VS Code 的扩展)
  • 使用http-server来自节点的模块(通过 npm 安装,然后从您的项目目录运行 http-server .)
  • 使用 http.server来自 python 的包
  • 使用 wamp(或灯)服务器

  • 总之不能用type="module"带文件协议(protocol)

    关于javascript - "access to script from origin ' null ' has been blocked by CORS policy"尝试使用导入的 js 函数启动 html 页面时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59912641/

    相关文章:

    jquery - 获取 HTML 对象之外的数据

    css - 如何用CSS强制div宽度拉伸(stretch)到它的内容而不是被它的容器限制?

    visual-studio-code - 如何在 Visual Studio Code 中禁用 "fake"右括号注释?

    javascript - 在函数内使用 "this"关键字访问全局属性

    javascript - 自愈蠕变

    javascript - 编辑 HTML/CSS 主题但似乎无法使其显示已售罄

    spring - Visual Studio代码+ Spring Boot项目更改spring.properties.additional-location等

    git - Visual Studio Code 中的 U 和 M 文件标记是什么?

    Javascript正则表达式匹配html中的json

    javascript - for javascript中的下一个循环括号