About Vue to eliminate repeated prompts when refreshing the page when the Token expires

About Vue to eliminate repeated prompts when refreshing the page when the Token expires

When the token expires, refresh the page. If the page initiates multiple requests to the backend when loading, repeated alarm prompts will be issued. After processing, the alarm will only be prompted once.

1. Problem phenomenon

The page has not been operated for a long time. When you refresh the page, the prompt "Token expired, please log in again!" pops up for the first time, then jumps to the login page, and then n backend return message prompts "Token expired" pop up.

2. Cause Analysis

The current page is initialized, and there are multiple calls to query system parameters from the backend. The code is as follows:

created () {
    //= ...
    // Get the required system parameters. Note: the getParameterClass method loads data asynchronously.
    // If you need to print observations, you need to process them through watch // Get the parameter category of the user type this.commonFuncs.getParameterClass(this,"user_type","userTypeList","userTypeMap");

    // Get the parameter category of user status for(var i = 0; i < this.userStatusList.length; i++){
      var item = this.userStatusList[i];
      var mapKey = parseInt(item.itemKey);
      this.userStatusMap.set(mapKey, item);
    }

    // Get the parameter class of gender this.commonFuncs.getParameterClass(this,"gender","","genderMap");

    // Get the parameter class of the department this.commonFuncs.getParameterClass(this,"department","","deptMap");

    // Get the role's parameter category this.commonFuncs.getParameterClass(this,"role","","roleMap");

    // Query user records this.queryUsers();
  },

These requests, which are axios calls, are performed asynchronously, so when you refresh the page, these requests are made almost immediately. Then, responses to these requests will be returned one after another.

The response is first processed by the following response interceptor:

// token-related response interceptor instance.interceptors.response.use(response => {  
  if (response) {
    switch (response.data.code) {
      case 3: //token is empty case 4: //token expired case 5: //token is incorrect localStorage.clear(); //Delete user information alert('token is invalid, please log in again!');
        // To jump to the login page router.replace({
              path: '/login',
        });
        break;
      case 6: //Access denied// Jump to 403 page router.replace({
          path: '/forbidden',
        });        
        break;
      default:
        break;
    }
  }
  return response;
}, error => {
  return Promise.reject(error.response.data.message) //Return the error message returned by the interface})

Then enter the code where the request is called:

 this.instance.getParameterClass(
      this.$baseUrl, {"classKey" : classKey}
    ).then(res => {
      //console.log(res.data);
      if (res.data.code == parent.global.SucessRequstCode){
        // If the query succeeds // Success code...
      }else{
        alert(res.data.message);
      }
    }).catch(error => {
      //alert('Query system parameters failed!');            
      console.log(error);
    });

Now the question:

For a request, if the token expires, the response interceptor will first pop up a warning prompt, and then there will be another prompt at the call site:

alert(res.data.message);

This repeats itself.

For multiple requests sent at the same time, a marker is needed to remember whether the token expiration has been prompted. The prompt is only given once. If it has been prompted, there is no need to prompt again.

3. Solution

3.1. Eliminate repeated reminders of token expiration in interceptors and request calls

Write a public method to check whether it is the return code of the intercepted processing, and put it in the /src/common/commonFuncs.js file. The code is as follows:

 /**
   * Determine whether the return code of the request is intercepted. Return true to indicate that the request is intercepted. * This method is used at the calling site. There is no need to process the error message of the intercepted return code. * @param {request return code} code 
   */
  isInterceptorCode(code){
    switch (code) {
      case 3: //token is empty case 4: //token expired case 5: //token is incorrect case 6: //access is prohibited return true;
      default:
        break;
    }
    return false;
  }

Then all calls to handle non-successful returns are changed to:

 if (!this.commonFuncs.isInterceptorCode(res.data.code)){
          alert(res.data.message);
        }

In this way, duplicate alerts for interception processing and call processing are eliminated.

3.2. Processing multiple requests with only one prompt

In the global variable file /src/common/global.js, add the token invalid flag. The code is as follows:

//global variable export default {
  // Request success return code SucessRequstCode: 0,

  // token invalid flag TokenInvalidFlag: 0
}

Then, modify the interceptor code:

// token-related response interceptor instance.interceptors.response.use(response => {  
  if (response) {
    switch (response.data.code) {
      case 0: //Normal// Reset token invalid flag Set global.TokenInvalidFlag = 0;
        break;            
      case 3: //token is empty case 4: //token expired case 5: //token is incorrect localStorage.clear(); //delete user information if (global.TokenInvalidCounter == 0){
          alert('token expired, please log in again!');
        }
        // Set the token invalid flag to 1
        global.TokenInvalidFlag = 1;
            
        // To jump to the login page router.replace({
              path: '/login',
        });
        break;
      case 6: //Access denied// Jump to 403 page router.replace({
          path: '/forbidden',
        });        
        break;
      default:
        break;
    }
  }
  return response;
}, error => {
  return Promise.reject(error.response.data.message) //Return the error message returned by the interface})

That is, when the token expiration message is received for the first time (TokenInvalidFlag=0 at this time), a prompt will be given, and then it will be set to 1 (TokenInvalidFlag=1 at this time). There will be no warning prompts for the responses to the subsequent requests. It is reset to 0 until a successful return code is received, indicating that the re-login is successful.

After testing, this processing achieves the expected effect, that is, when the token expires, the page is refreshed and only one alarm is prompted.

Author: Arab 1999 Source: http://www.cnblogs.com/alabo1999/ The copyright of this article is shared by the author and Cnblog Park. Reprinting is welcome, but this statement must be retained without the author's consent, and the original link must be given in a prominent position on the article page, otherwise the right to pursue legal liability is reserved. Develop good habits and give a thumbs up to good articles.

This is the end of this article about Vue eliminating repeated prompts for refreshing the page when the Token expires. For more relevant content about Vue refreshing the page, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • SpringBoot JWT implements token login refresh function
  • Detailed explanation of uniapp painless token refresh method
  • Detailed explanation of JWT refresh token in ASP.NET Core Web Api
  • Automatically refresh token operation when token expires during request
  • Implementation of SpringSecurity Jwt Token automatic refresh
  • Refresh token process analysis based on springboot+jwt
  • Example code of axios interceptor token refresh mechanism under vue
  • Laravel (Lumen) solves the problem of JWT-Auth refreshing token
  • How to achieve seamless token refresh

<<:  Solve MySQL deadlock routine by updating different indexes

>>:  Zabbix3.4 method to monitor mongodb database status

Recommend

Steps to configure IIS10 under Win10 and support debugging ASP programs

Microsoft IIS IIS (Internet Information Server) i...

Limiting the number of short-term accesses to a certain IP based on Nginx

How to set a limit on the number of visits to a c...

Problems and solutions encountered when installing mininet on Ubuntu 16.04.4LTS

Mininet Mininet is a lightweight software defined...

How to design the homepage of Tudou.com

<br />I have been working in front-end for s...

Things to note when writing self-closing XHTML tags

The img tag in XHTML is so-called self-closing, w...

Specific use of CSS content attribute

The content attribute is generally used in the ::...

Writing a web calculator using javascript

This article mainly records the effect of using j...

Let's talk in detail about the difference between unknown and any in TypeScript

Table of contents Preface 1. unknown vs any 2. Th...

Solution to invalid Nginx cross-domain setting Access-Control-Allow-Origin

nginx version 1.11.3 Using the following configur...

A line of CSS code that crashes Chrome

General CSS code will only cause minor issues wit...

How to install mysql in docker

I recently deployed Django and didn't want to...

Data storage implementation method in WeChat applet

Table of contents Global variable globalData Page...