我正在使用本地服务器开发一个项目。
在这个项目中,我使用模块,所以我的
index.html
包含:
<script src="js/index.js" type="module"></script>
我的
index.js
包含:
import {} from "/js/randomModule.js";
import {} from "/js/randomModule.js";
...
一切都运行得很完美,但是当我想直接在浏览器上使用该项目,而不需要服务器时,这就是问题:
Access to the script at 'file:///C:/Users/myFolder/js/index.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.
index.html:54
GET file:///C:/Users/myFolder/js/index.js net::ERR_FAILED
那么,有没有一种方法可以在没有服务器的情况下直接在浏览器中使用 javascript
type="module"
?
您需要注意本地测试——如果您尝试加载 本地 HTML 文件(即使用 file:// URL),您将遇到 CORS 由于 JavaScript 模块安全要求而导致的错误。你需要做 您通过服务器进行测试。
很遗憾,不,你不能在没有服务器的情况下直接在浏览器中运行带有“type='module'”的JS。
有很多选项可以运行本地服务器:W/X/LAMP 堆栈、oldschool
php -S localhost:8080
、带有express.js 和静态目录的节点等