vue3+vue-router4 路由HTML5模式(createWebHistory ),编译后部署到nginx,点击路由跳转正常,但是刷新页面报404

import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/home',
    },
    {
      path: '/index/home',
      component: () => import('../views/index/Home.vue'),
    },
    {
      path: '/home',
      component: () => import('../views/home/Index.vue'),
    },
    {
      path: '/me',
      component: () => import('../views/me/Index.vue'),
    },
  ],
})

router.beforeEach((to, from) => {
  return true
})

export default router

不兼容:

    server {
        listen 80;
        server_name localhost chat.test.com;

        #配置根目录
        location / {
            root    /temp/test;
            index  index.html index.htm;
            add_header Content-Security-Policy upgrade-insecure-requests;
        }
    }  

解决方案:

    server {
        listen 80;
        server_name localhost chat.test.com;

        #配置根目录
        location / {
            root    /temp/test;
            #index  index.html index.htm;
            try_files $uri $uri/ /index.html;
            add_header Content-Security-Policy upgrade-insecure-requests;
        }
    }  

参考链接

https://router.vuejs.org/zh/guide/essentials/history-mode.html#nginx

人工智能学习网站

https://chat.xutongbao.top

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue 路由history 模式下,刷新页面会导致 404 错误的出现,这是因为浏览器会向服务器发送请求,但服务器并没有对应的路由,因此就会返回 404 错误。解决这个问题的方法有两种: 1. 配置后端服务器 如果你的 Vue 项目部署在 Apache 或 NginxWeb 服务器上,你可以配置服务器来处理这个问题。具体做法是,在服务器上配置一个重定向规则,将所有的 URL 请求都重定向到 index.html 文件上。以 Apache 服务器为例,可以在 Apache 的配置文件(如 httpd.conf)中添加以下规则: ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L] </IfModule> ``` 这个配置将所有的 URL 请求都重定向到 index.html 文件上,这样即使刷新页面,服务器也会返回正确的内容。 2. 使用 hash 模式 如果你不想在服务器上配置重定向规则,你可以考虑使用 hash 模式。在 hash 模式下,Vue 会使用 URL 中的 # 符号来表示路由,这样即使刷新页面,浏览器也只会重新加载 index.html 文件,而不会向服务器发送请求。要启用 hash 模式,只需要在 Vue 路由的配置中添加以下代码: ``` const router = new VueRouter({ mode: 'hash', routes: [...] }) ``` 这样就可以启用 hash 模式了。需要注意的是,hash 模式下,URL 中的 # 符号后面的内容不会被发送到服务器,因此你需要在前端代码中使用 JavaScript 来解析 URL 中的 hash 值,并根据这个值来渲染不同的页面。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

徐同保

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值