html 上的简单 JavaScript 导入/导出不起作用

问题描述

我只是在导出/导入时做了一个简单的 JavaScript 并将其插入到 html 我有一个错误“未捕获的语法错误:无法在模块外使用导入语句”。我在 StackOverflow 上进行了搜索,发现脚本类型必须声明为“模块”。 添加此后,我收到错误“class02.html:1 Access to script at 'file:///C:/xxx/yyyyy/animal.js' from origin 'null' has been Blocked by CORS policy: Cross origin requests仅支持以下协议方案:http、data、chrome、chrome-extension、chrome-untrusted、https。"

下面是我的代码: 动物.js:

export class Animal {
    constructor(type,legs) {
        this.type = type;
        this.legs = legs;
    }
}

class02.html:

<html>
    <head>
        <script type="module">
            import { Animal } from './animal.js';
            let cat = new Animal('Cat',4);
            cat.legs = 3;
            alert(cat.legs);        
        </script>
    </head>
    <body>
    <h1>test</h1>
    </body>
</html>

class02.html 和animal.js 都在我C 盘的同一个目录下。 有人可以帮我解决这个问题吗。

解决方法

要修复 CORS 错误,您需要在服务器上运行 html 文件。您可以在您的机器上安装 apache 或 nginx 并在其上运行您的代码。就我而言,我在 Windows 10 上使用 Wamp 并将其移至 www 文件夹。它也有效。