0

我只是在导出/导入上做了一个简单的 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。"

下面是我的代码:animal.js:

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

类02.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 盘的同一个目录中。有人可以帮我解决这个问题。

4

1 回答 1

1

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

于 2021-03-04T21:33:25.443 回答