正文 3992字数 5,246阅读


vue项目部署后刷新页面404的原因和解决方案
vue项目打包部署上线后发现项目是可以正常运行,
但是使用F5或者浏览器的刷新按钮直接变成404页面

mode: 'history' 和 mode: 'hash' 的问题可能与 Vue Router 的版本有关。在 Vue Router 4.x 中,mode 选项已经被废弃,取而代之的是直接使用 history 选项来指定路由模式。

vue路由两种模式的区别
new Router({ mode: 'hash', // history routes: [], ... })
Run code
Cut to clipboard


    1.hash 模式(默认)的访问URL中有 # 字符,history模式的URL没有带#,外观上history模式比hash模式好看些;

    2.hash模式通过监听浏览器的onhashchange()事件变化,查找对应的路由规则;history模式是利用h5的history中新增的两个API pushState() 和 replaceState() 和一个事件onpopstate监听其URL变化;

    3. hash模式能兼容到IE8,history模式 只能兼容到 IE10;

    4.由于 hash 值变化不会导致浏览器向服务器发出请求,而且 hash 改变会触发 hashchange 事件(hashchange只能改变 # 后面的url片段);
    虽然hash路径出现在URL中,但是不会出现在HTTP请求中,对服务器完全没有影响,因此改变hash值不会重新加载页面,基本都是使用 hash 来实现前端路由的。

    重点:hash模式在每次刷新页面时是直接更改“#”后的路径,history模式每次刷新会重新像服务器重新请求资源,但是服务器会把vue的路由地址当成文件路径访问(如: /pages/index),服务器又没有这个文件路径,且服务端没有配置相应的路由重定向,就会访问404,
    也就是本文开头提到的问题;history模式的好处是可以进行修改历史记录,并且不会立刻像后端发起请求。不过如果对于项目没有硬性标准要求,我们可以直接使用hash模式开发。

    解决404问题

    1.直接使用hash模式无404问题;
    new Router({ mode: 'hash', ... })
    Run code
    Cut to clipboard


      2.使用history模式需服务器进行配置,以下是服务器配置;
      new Router({ mode: 'history', ... })
      Run code
      Cut to clipboard


        Nginx:
        location / { try_files $uri $uri/ /index.html; #解决页面刷新404问题 }
        Run code
        Cut to clipboard


          Apache:
          <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L] </IfModule>
          Run code
          Cut to clipboard


            当项目部署到服务器子文件路径时资源404问题
            1.如比我们将项目部署到了h5文件夹中,这时候的访问路径应该是http://127.0.0.1:8080/h5/,访问后会出现js和css资源404,
            因为配置默认是指向到绝对路径'/',也就是根目录,但是根目录没有这些资源文件,就会让项目访问失败。

            2.如何解决,以下从vue2.0和vue3.0分别修改配置。
            vue2.0:
            // vue.config.js module.exports = { publicPath: '/h5/', ... }
            Run code
            Cut to clipboard


              // router const createRouter = () => new Router({ mode: 'history', base: '/h5', ... })
              Run code
              Cut to clipboard


                vue3.0:
                // vite.config.ts export default defineConfig({ base:'/h5/', ... })
                Run code
                Cut to clipboard


                  // router const router = createRouter({ history: createWebHistory('/h5'), routes: [] });
                  Run code
                  Cut to clipboard


                    src\router\index.js
                    import HomeView from '../views/HomeView.vue' import { createRouter, createWebHistory } from 'vue-router' // import { createRouter, createWebHashHistory } from 'vue-router'; const router = createRouter({ // history: createWebHashHistory(import.meta.env.BASE_URL), history: createWebHistory(import.meta.env.BASE_URL), routes: [ { path: '/', name: 'home', component: HomeView, }, { path: '/rouacc', name: 'rouacc', component: () => import('@/views/rouacc.vue'), }, { path: '/menu', name: 'menu', component: () => import('@/views/menu.vue'), }, { path: '/about', name: 'about', // route level code-splitting // this generates a separate chunk (About.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import('../views/AboutView.vue'), }, ], }) export default router
                    Run code
                    Cut to clipboard


                      使用 history 模式
                      import { createRouter, createWebHistory } from 'vue-router'; const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes: [ { path: '/', name: 'home', component: HomeView, }, // 其他路由 ], });
                      Run code
                      Cut to clipboard


                        使用 hash 模式
                        import { createRouter, createWebHashHistory } from 'vue-router'; const router = createRouter({ history: createWebHashHistory(import.meta.env.BASE_URL), routes: [ { path: '/', name: 'home', component: HomeView, }, // 其他路由 ], });
                        Run code
                        Cut to clipboard


                          关键点
                          createWebHistory:用于创建基于 history 模式的路由。
                          createWebHashHistory:用于创建基于 hash 模式的路由。
                          import.meta.env.BASE_URL:这是 Vite 提供的环境变量,表示项目的基础 URL。

                          问题排查
                          如果你发现 mode: 'hash' 无效,可能是因为你在 Vue Router 4.x 中仍然使用了旧版的配置方式。确保你使用的是 createWebHashHistory 来启用 hash 模式。