vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > vue页面刷新404

vue项目页面刷新后报404的解决方法

作者:悟能不能悟

vue项目页面正常访问,但是刷新后报404,这种情况通常是由于 前端路由​ 和 浏览器直接访问​ 的差异导致的,主要有以下几个原因和解决方案,下面我们就来详细介绍一下吧

这种情况通常是由于 前端路由​ 和 浏览器直接访问​ 的差异导致的。主要有以下几个原因和解决方案:

主要原因

1. 路由模式问题(History vs Hash)

// 如果使用 history 模式,需要服务器配置
const router = new VueRouter({
  mode: 'history', // 需要服务器支持
  // mode: 'hash',  // 直接访问不会有问题,但URL有#号
  routes: [...]
})

2. 服务器配置问题

当直接输入URL时,浏览器会向服务器请求该路径,如果服务器没有正确配置,会返回404。

解决方案

方案1:配置服务器重定向

Nginx 配置:

location / {
  try_files $uri $uri/ /index.html;
}

Apache 配置(.htaccess):

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

方案2:使用 Hash 模式

const router = new VueRouter({
  mode: 'hash', // URL会包含 #/path
  routes: [...]
})

方案3:开发环境配置(webpack-dev-server)

vue.config.js中:

module.exports = {
  devServer: {
    historyApiFallback: true,
    // 或者更详细的配置
    historyApiFallback: {
      rewrites: [
        { from: /.*/, to: '/index.html' }
      ]
    }
  }
}

检查步骤

确认当前路由模式:

console.log(router.mode) // 查看是 history 还是 hash

检查路由配置:

// 确保路由正确定义
const routes = [
  {
    path: '/your-path', // 你访问的路径
    component: YourComponent,
    name: 'YourRoute'
  }
]

验证路由跳转:

<template>
  <!-- 这两种方式应该都能工作 -->
  <router-link to="/your-path">跳转</router-link>
  <button @click="$router.push('/your-path')">编程式导航</button>
</template>

实际示例

假设你的路由配置:

// router.js
const routes = [
  {
    path: '/user/:id',
    component: UserProfile,
    name: 'user'
  }
]

直接访问问题:

解决方案:

// vue.config.js
module.exports = {
  devServer: {
    historyApiFallback: true
  },
  // 生产环境构建路径
  publicPath: process.env.NODE_ENV === 'production' ? '/' : '/'
}

总结

你用的是哪种服务器环境?我可以提供更具体的配置方案。

到此这篇关于vue项目页面刷新后报404的解决方法的文章就介绍到这了,更多相关vue页面刷新404内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文