SoFunction
Updated on 2025-04-06

Detailed explanation of how vue2 realizes the invisible refresh token

introduction:

In a web application, users need authentication and authorization to access protected resources. To implement authentication and authorization functions, it is usually necessary to use a token to identify the user's identity and verify its permissions. However, Tokens sometimes limit their expiration date to ensure security.

When the token expires, the application returns a 401 (unauthorized) error, prompting the user to log in again or refresh the page. This can affect user experience and process and can cause performance issues in your application.

Therefore, in order to improve the user experience and reliability of the application, the technology of refreshing the token invisible is usually used to automatically refresh expired tokens. This way, even if the token expires, users can continue to use the application without any interference. In addition, refreshing the token can also improve the security and stability of the application because it can effectively prevent the token from being maliciously exploited or attacked.

It should be noted that in the process of realizing a senseless refresh token, you need to pay attention to protecting the security of user data and complying with relevant security standards and laws and regulations. At the same time, the specific implementation method needs to be adjusted according to the application needs and the design of the back-end interface.

Installation dependencies

Now we start writing vue2 front-end code

First, make sure that Axios and related dependencies are installed.

npm install axios

Create an Axios instance and make request encapsulation

existsrc/utils/Create an Axios instance in the file and perform relevant configuration.

import axios from "axios";
 
const service = ({
  baseURL:
    .NODE_ENV !== "production"
      ? .VUE_APP_BASE_API
      : .VUE_APP_BASE_API_RUL,  
  timeout: 10000, // Timeout time});
 
// request interceptor// You can do some processing on the request before sending it// For example, add tokens to encrypt the request parameters uniformly(
  (config) => {
    const token = ("token");
    token && ( = token);
    ["Content-Type"] = "application/json;charset=utf-8";
    ["Authorization"] = "Bearer " + token; // Set request header    return config;
  },
  (error) => {
    return ("Network exception, please try again later" + error);
  }
);
 
// response interceptor// The results can be processed uniformly after the interface responds(
  (response) => {
    if ( == 401) {
      let userInfo = {};
       =  .VUE_APP_TOKEN.split(",")[0];
       =  .VUE_APP_TOKEN.split(",")[1];
      // Here you need to call the login interface and re-get the token      return refreshToken(userInfo).then((newToken) => {
        // Update local storage tokens        ("token", newToken);
        // Resend the original request        return service();
      });
    }
 
    let res = ;
    // Compatible with string data returned by the server    if (typeof res === "string") {
      res = res ? (res) : res;
    }
    return res;
  },
  (error) => {
    return ("Network exception, please try again later" + error);
  }
);
function refreshToken(userInfo) {
  return new Promise((resolve, reject) => {
    // Call the login interface to re-get the Token    axios  
      .post(`${.VUE_APP_BASE_API}/pc_admin/login`, {    
        ...userInfo,
      })
      .then((response) => {
        resolve();
      })
      .catch((error) => {
        reject(error);
      });
  });
}
 
export default service;

Axios instance using encapsulated

Introduce an encapsulated Axios instance where it needs to be sent and use it to send the request.

//
import request from "./http";
// Test interfaceexport function getListApi(params) {
    return request({
        url: "/pc_admin/article", 
        method: "get",
        params: params,
    });
}
 

Written at the end

Through the above code, when sending a request using Axios, the token expires will be automatically processed and the token is refreshed without any sense. This can improve the user experience and security of the application.

The above is the detailed explanation of the way vue2 realizes the invisible refresh token. For more information about vue2 invisible refresh token, please pay attention to my other related articles!