You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3+Vite项目打包后直接打开index.html遇CORS政策错误求助

解决Vue3+Vite打包后直接打开index.html的CORS问题
  • 修改Vite配置文件(vite.config.js或vite.config.ts),将资源基础路径设为相对路径:

    export default defineConfig({
      // 保留原有其他配置
      base: './', // 关键配置:让资源路径基于当前index.html的位置
    })
    
  • 若使用了Vue Router,需将路由模式切换为hash模式:

    import { createRouter, createWebHashHistory } from 'vue-router'
    
    const router = createRouter({
      history: createWebHashHistory(), // 替换原有的createWebHistory()
      routes: [/* 你的路由配置列表 */]
    })
    
  • 重新执行npm run build命令,生成更新后的dist目录。

  • 将整个dist文件夹发送给对方,对方直接打开其中的index.html即可正常访问网站。

原因说明:

默认打包配置使用绝对路径(base: '/'),当通过file://协议打开本地html时,浏览器会尝试从系统根目录加载资源,既会出现路径匹配错误,又会触发浏览器对file://协议的CORS限制。改为相对路径后,资源会基于当前index.html的位置加载,解决了路径和跨域问题。另外history路由依赖服务端URL重写,本地file://协议无法支持,因此必须切换为hash模式。

内容的提问来源于stack exchange,提问作者gorczyca

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 12:02:45