VS Code中Vue.js项目打开index.html出现CORS错误的解决方法
我刚接触Vue.js,使用Visual Studio Code,已按照Vue官网关于VS Code搭配Volar扩展的所有指引操作。示例项目包含HelloWorld.vue的"hello world"页面,但直接双击打开index.html时显示空白页,Chrome控制台报CORS错误:
Access to script at 'file:///C:/Users/quilk/Documents/testvue/main.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome, https, chrome-untrusted.
项目核心代码如下:
index.html代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="icon" href="/favicon.ico"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vite App</title> </head> <body> <div id="app"> </div> <script type="module" src="/src/main.js"></script> </body> </html>
main.js代码
import { createApp } from 'vue' import App from './App.vue' import './assets/main.css' createApp(App).mount('#app')
未修改任何示例代码,请问如何操作才能正常运行示例.vue组件?
问题核心在于直接打开html文件使用的是file协议,而ES模块(script type="module")不允许通过file协议加载资源,浏览器的CORS机制会拦截这类请求。必须通过本地开发服务器运行项目,步骤如下:
- 打开VS Code终端(快捷键`Ctrl+``),确保当前路径为项目根目录
- 若未安装依赖,先执行:
npm install - 启动本地开发服务器:
npm run dev - 终端会输出本地访问地址(如
http://localhost:5173),复制该地址到浏览器打开,即可正常显示HelloWorld页面
补充:Vue官方快速指引隐含了使用开发服务器的步骤,只是未强调不能直接打开html文件。用Vite创建的Vue项目必须通过开发服务器运行,因为Vite需要处理.vue文件的编译、模块打包等工作,直接打开html文件无法触发这些流程。
内容的提问来源于stack exchange,提问作者quilkin

