Vue implements automatic jump to login page when token expires

Vue implements automatic jump to login page when token expires

The project was tested these days, and the tester reported a bug to me, saying that the token has expired and the route should automatically jump to the login page to allow the user to log in again. Let me first talk about some prerequisites.

1: The token validity period of our company is set to one hour in the production environment. When the token expires, all interfaces return directly.
2: Each time the route jumps, the token will be judged. A global beforeEach hook function is set. If the token exists, it will jump to the page you need, otherwise

Jump directly to the login page and let the user log in to retrieve the token

Information returned by the interface

{
 code:10009,
 msg:'token expired',
 data:null
}

Global routing hook function

router.beforeEach(async(to, from, next) => {
//Get token
  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
  //token exists, if the current redirected route is the login interface if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
    //Here, we remove the user's permissions to determine whether the user has permission to access this route} catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
  } else {
    //token does not exist if (whiteList.indexOf(to.path) !== -1) {
    //If the route to be redirected is in the whitelist, jump to next()
    } else {
    //Otherwise jump to the login page next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

So I directly intercept all requests. When the response data returns code 10009, I directly clear the user information and reload the page. I simplified the code because when the user logs in, the token, name, and permission information will be stored in the store/user.js file, so as long as the token expires, the information in the user file will be cleared. In this way, after the token expires, when the page is refreshed or the component is jumped, the global beforeEach judgment will be called. When the token information does not exist, it will jump directly to the login page.

import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, 
  timeout: 5000 
})
// Carry the token when sending the request service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['sg-token'] = getToken()
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    console.log(response.data)
    const res = response.data

    // Token expired, return to login interface if (res.code === 10009) {
      store.dispatch('user/logout').then(() => {
        location.reload(true)
      })
    }
    return res
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.msg,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service

Well, that’s all about token sharing. Replace the above code with your data according to your project.

This is the end of this article about how to use Vue to automatically jump to the login page when the token expires. For more information about how to automatically jump to the login page when the token expires, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to implement Vue click button route jump to specified page
  • vue jumps to the page and opens a new window, carrying and receiving parameters
  • Summary of the four common methods and differences of Vue jump page
  • How to implement page jump in Vue project
  • How to use vuex to jump to the page
  • Solution for Vue routing this.route.push jump page not refreshing
  • How does Vue realize the jump between pages of this project

<<:  URL Rewrite Module 2.1 URL Rewrite Module Rule Writing

>>:  Detailed explanation of HTML table tags (suitable for beginners)

Recommend

Use semantic tags to write your HTML compatible with IE6,7,8

HTML5 adds more semantic tags, such as header, fo...

How to build a MySQL PXC cluster

Table of contents 1. Introduction to PXC 1.1 Intr...

Detailed explanation of MySQL clustered index and non-clustered index

1. Clustered Index Table data is stored in the or...

Detailed installation and configuration tutorial of PostgreSQL 11 under CentOS7

1. Official website address The official website ...

HTTP Status Codes

This status code provides information about the s...

Vue routing returns the operation method of restoring page status

Route parameters, route navigation guards: retain...

js implements custom drop-down box

This article example shares the specific code of ...

Two types of tab applications in web design

Nowadays, tabs are widely used in web design, but...

Detailed explanation of this pointing in JS arrow function

Arrow function is a new feature in ES6. It does n...

Example code for implementing image adaptive container with CSS

There is often a scenario where the image needs t...

Summary of knowledge points about null in MySQL database

In the MySQL database, null is a common situation...

Detailed explanation of common methods of JavaScript Array

Table of contents Methods that do not change the ...

How to quickly deploy an Elasticsearch cluster using docker

This article will use Docker containers (orchestr...

Why the CSS attribute value clear:right does not work in detail

Using the clear property to clear floats is a comm...