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

Vue 2.7 + Vite二级子路由刷新404问题解决方法

解决Vue 2.7 + Vite二级路由刷新404问题

问题原因

刷新二级路由/x/y时,浏览器会以当前路径/x/y为基准加载资源,导致原本的src/main.ts被错误解析为/x/src/main.ts;同时history模式下服务器无法识别/x/y这个路由路径,直接返回404。

解决方案

1. 修正index.html中的资源引用路径

打开项目根目录的index.html,将资源引用改为绝对路径或适配Vite的环境变量:

  • 根路径部署场景:
<script type="module" src="/src/main.ts"></script>
  • 自定义base路径场景(适配部署子目录):
<script type="module" src="%VITE_BASE_URL%src/main.ts"></script>

2. 配置Vite的history路由 fallback

在vite.config.ts中添加server.historyApiFallback配置,确保所有路由请求都重定向到index.html:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue2'
import { fileURLToPath, URL } from 'node:url'

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
    },
  },
  server: {
    historyApiFallback: true
  }
})

3. 确认Vue Router的base配置

确保base值与实际部署路径匹配,dev环境下import.meta.env.BASE_URL默认值为'/',无需额外修改:

const router = new VueRouter({
  mode: "history",
  base: import.meta.env.BASE_URL,
  routes: routes
});

完成以上配置后,重启pnpm run dev,刷新/x/y即可正常加载页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 18:01:16