解决Vue中使用history路由模式出现404的问题

背景

vue中默认的路由模式是hash,会出现烦人的符号#,如http://127.0.0.1/#/
改为history模式可以解决这个问题,但是有一个坑是:强刷新、回退等操作会出现404。

Vue改用History路由模式

修改src/router/index.js

export default new Router({
  mode: 'history',            //改为history模式
  routes: [
    {
      path: '/pub',
      component:Empty
    }
  ]
})

解决History模式404的问题
原理:增加中间件的配置(如nginx),所有未匹配到的路由都返回index.html。
官方文档:https://router.vuejs.org/zh/guide/essentials/history-mode.html

这里介绍一种官方文档没有的,使用Golang的Gin框架解决404的问题。

router := gin.New()
router.Use(gin.Recovery())

// 注册静态文件
router.Static("/pub", "./pub")
router.Static("/static", "./pub/static")
router.LoadHTMLGlob("./pub/*.html")         //加载index.html文件

//处理首页的访问
router.GET("/", func(c *gin.Context) {
    c.Redirect(http.StatusFound, "./pub/index.html")
})

//【关键点】:把所有找不到路由的请求,都返回index.html
router.NoRoute(func(c *gin.Context) {
    c.HTML(http.StatusOK,"index.html",nil)
})

//启动http服务
router.Run()

关键是这行代码:

router.NoRoute(func(c *gin.Context) {
    c.HTML(http.StatusOK,"index.html",nil)
})

写在后面

既然所有找不到路由的请求都返回index.html,那真正404的请求就不会显示404了。
所以在vue的src/router/index.js中要这样设置

export default new Router({
  mode: 'history',            
  routes: [
    {
      path: '/pub',
      component:Empty
    },
    {
      path: '*',            //其他路由显示404
      component: NotFound,
    }
  ]
})

 


————————————————
版权声明:本文为CSDN博主「NetRookieX」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/NetRookieX/article/details/121448145

posted @ 2022-11-16 16:47  张志健  阅读(3520)  评论(1编辑  收藏  举报