zoukankan      html  css  js  c++  java
  • Vue实现远程获取路由与页面刷新导致404错误的解决

    一、背景

      先简单介绍一下现在项目情况:前后端分离,后端服务是Java写的,前端是Vue+ElementUI。

      最近的一个需求是:通过后端Api去获取前端路由表,原因是每个登录角色对应的前端路由表可能是不一样的(权限问题)

    二、遇到的问题

       因为前端Vue+ElementUI项目是单页应用——即只有一个index.html页面,如果路由从远程获取的话,每次F5或点击刷新按钮刷新页面的时候,就会找不到对应的路径而报404错误  

    三、解决方案

      1、通过api远程获取路由,然后在前端生成对应路由

    /* 
      将 服务器获得的[路由json字符串]转换成可访问的[前端路由组件] 
      @remoteRouterMap 服务器获得的[路由json字符串]
    */
    function transformJsonToRouter(remoteRouterMap) {
      const accessedRouters = remoteRouterMap.filter(route => {
        if (!route.component) {
          route.component = Layout
        }else {
          route.component = route.component.replace("@/views/","")
          route.component = _import(route.component)
        }
        if (route.children && route.children.length) {
          route.children = transformJsonToRouter(route.children)
        }
        return true
      })
    
      return accessedRouters
    }

           2、将路由模式改成history模式(vue默认是hash模式)

    export default new Router({
      mode: 'history', //后端支持可开
      scrollBehavior: () => ({ y: 0 }),
      routes: constantRouterMap,
      linkActiveClass: 'is-active'
    })

            

            3、在nginx中设置将404错误指向index文件

    location / {
      try_files $uri $uri/ /index.html;
    }
  • 相关阅读:
    C语言I博客作业04
    C语言I博客作业03
    C语言1博客作业02
    作业1
    C语言||作业01
    C语言寒假大作战04
    C语言寒假大作战03
    C语言寒假大作战02
    C语言寒假大作战01
    笔记本
  • 原文地址:https://www.cnblogs.com/mumue/p/10226865.html
Copyright © 2011-2022 走看看