SoFunction
Updated on 2025-04-07

How to use refresh_token to achieve a senseless refresh page

The steps are as follows:

1-token expires. Get new token according to refresh_token and re-get data

2-Create a new axios instance [Use request to prevent re-entering request interception and request response and entering a dead loop]

3-According to the corresponding response value of the request, is it 401? Yes: It means that the token has expired

Then make a judgment on the user in the store:{token:'*',refresh_token:'Whether the refresh_token and user objects in **'} exist? If it does not exist, it means that you have not logged in before. Go directly to log in.

4-Send a new request using the newly created axios instance object requestFreshToken The password in the headers carries refresh_token

5-After obtaining the token, reassign the value to the token in user

6-Restore user into store

7-Retrieve the data that was not obtained because the token was invalid. Use the request parameter directly from the error object [The request data of the token that had failed was saved here]

Specific implementation

The code is as follows:

import axios from "axios";

import store from "@/store";
import router from "@/router";

import jsonBig from "json-bigint";

import { Toast } from "vant";

// var json = '{ "value" : 9223372036854775807, "v2": 123 }'
// // ((json),777888);
// ((json).(),88888);

const request = ({
  // There will be no big numbers problem with all corresponding data  transformResponse: [
    function(data) {
      try {
        // If the conversion is successful, return the converted data result        return (data);
      } catch (err) {
        // If the conversion fails, wrap it in a unified data format and return        return {
          data
        };
      }
    }
  ]

  //baseURL: ""
});

// Create a new axios instance object The purpose of this is to not enter the previous request interception and response to prevent entering the dead loopconst requestFreshToken = ();

// Add a request interceptor(
  function(config) {
    // What to do before sending a request    //(config, 9999);
    // if (('SET_TOKEN')) {
    //      = 'Bearer ' + (('SET_TOKEN')).token
    // }

    if () {
       = "Bearer " + ;
    }
    return config;
  },
  function(error) {
    // What to do about the request error    return (error);
  }
);

// Add a response interceptor(
  function(response) {
    (response, 3);

    return response;
  },
  async function(error) {
    (, 222);
    // Do something to respond to errors    // Do something about the response data    const status = ;
    if (status == 400) {
      // Error in request parameters      ("Error request parameter");
    } else if (status == 401) {
      // User authentication failed. If the token is passed but the token expires, it will return 401.
      /*
				 token expired Get new token according to refresh-token
				 1-Send a request Get a new token
				 2-Resend the request according to the new token and realize the invisible refresh
			
			  */
      const { user } = ;
      if (!user || !user.refresh_token) {
        // No tokens        return ("/login");
      }
      // There is a token but the token expires      try {
        // Get new token according to refresh_token        const { data } = await requestFreshToken({
          method: "PUT",
          url: "/v1_0/authorizations",
          headers: {
            Authorization: "Bearer " + user.refresh_token
          }
        });
        // Reassign the token in user         = ;
        // Restore the new user object to the store        ("setUser", user);
        // After resending the request here, you will use request to intercept the request above and carry the new token you just saved again.        return request();
      } catch (error) {}
      // Log in directly after catching the exception      return ("/login");

      ("User authentication failed");
    } else if (status == 403) {
      // The client does not have permissions      ("The client does not have permission");
    } else if (status == 405) {
      // The request method is not supported      ("Request method is not supported");
    }
    return (error);
  }
);

export default request;

This is the article about how React uses refresh_token to achieve a senseless refresh page. For more related React refresh_token, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!