This post is also posted on my blog at 😄

Writing in the front

After the front and back ends are separated, the responsibility of controlling route hops is transferred to the front end, and the back end only returns an HTML document and provides various interfaces to the front end. The following two projects we use as examples both use VUE as the basic framework, one is SPA application and the other is multi-page application, both of which are controlled and rendered by the front end.

The overall train of thought

The idea is to add a route with path: ‘/404’ to the front routing table and render the corresponding 404 page. In addition, configure a rule that automatically redirects users to the 404 page when all routes in the accessible routing table cannot be matched. Here are my different implementations for single and multiple pages.

SPA 404 route configuration

Single-page applications configure 404 pages, and distinguish between the two cases:

The routing table is fixed

If the SPA routing table is fixed, configuring the 404 page is very simple. You only need to add a route with path 404 to the routing table and configure a route with path * at the bottom of the routing table to redirect the route to route 404.

(Because the routing table is matched from top to bottom, make sure that any matching rule is placed at the bottom; otherwise, all routes under this routing rule will be forwarded to 404 and cannot be matched correctly.)


// router.js
export default new Router({
  mode: 'history'.routes: [
    // ...
    {
      name: '404'.path: '/ 404'.component: (a)= > import('@/views/notFound.vue')}, {path: The '*'.// Pay special attention to the bottom here
      redirect: '/ 404'}],})Copy the code

Dynamic routing table generation

If the routing table is dynamically generated, the routing table is divided into two parts: the basic routing table and the routing table that needs to be dynamically generated based on user permission information.

In this project, dynamic route generation adopts the addRoutes method of VUE-Router, which will inject new routing rules at the end of the original routing table array. Since any rule that matches a 404 page must be redirected to the bottom of the routing table, I extract the rule that is redirected to the bottom of the routing table. After dynamic route injection, I inject the redirection rule to ensure that the rule is redirected to the bottom of the routing table.

// router.js
export default new Router({
  mode: 'history'.routes: [
    // ...
    {
      name: '404'.path: '/ 404'.component: (a)= > import('@/views/notFound.vue')},/ /... other codes],})Copy the code
// notFoundRouterMap.js

export default[{path: The '*'.redirect: '/ 404'}]Copy the code
// main.js

/ /... other codes
router.beforeEach((to, from, next) = > {
  new Promise((resolve, reject) = > {
    if (getCookie(tokenName)) {
      if(! getInfo()) {Promise.all([store.dispatch('getBasicInfo'), store.dispatch('getUserDetail')]).then(res= > {
          store.dispatch('GenerateRoutes', { roles }).then((a)= > { 
          // Generate an accessible routing table based on user permissions
            router.addRoutes(store.getters.addRouters) // Dynamically add the accessible routing table
            router.addRoutes(NotFoundRouterMap) // Add 404 and redirect routing rulesresolve({ ... to,replace: true }) // Re-load the route once, and make way for the following else judgment after the table is updated successfully})})}else {
        / /... other codes}}else {
      window.location.href = '/login.html'
    }
  }).then(res= > {
    if (res) {
      next(res)
    } else {
      next()
    }
  }).catch(err= > {
    new Error(err)
    next(false)})Copy the code

404 route configuration for multi-page applications

Multi-page apps differ from SPAs in that each page has its own set of rules, and each page may or may not have its own set of 404 page styles. In this case, you cannot add routing rules dynamically.

The scheme I use is to judge the routing match in the global navigator beforeEach, at this time, I need to use the matched array in the Vue navigator. If none match, the 404 page is redirected. Of course, the 404 page is also set as a separate page.

// permission.js

/ /... other codes
router.beforeEach((to, from, next) = > {
  new Promise((resolve, reject) = > {
    / /... other codes
  }).then(res= > {
    if(! to.matched.length) {window.location = '/error.html#/404'
        return
      } 
    if (res) {
      next(res)
    } else {
      next()
    }
  }).catch(err= > {
    new Error(err)
    next(false)})Copy the code

This solution allows each page to have its own 404 page routing rules, and configures the default 404 page for routes that do not have 404 pages, which feels friendly.

The last

This is the solution I used in the development process, if there is a better method, please do not hesitate to inform, thank you!

When doing this practice, draw lessons from many brothers’ articles, listed here, thanks to the table!

  1. Background system permission control based on Vue2.0
  2. Dynamic routing with addRoutes
  3. how to create a 404 component in vuejs using vue-router