Axios is a network front-end request framework, with the basic usage as follows:
1. Basic usage of Axios:
const response = await ({ baseURL: "", headers: { 'Content-Type': 'application/json', }, }).post<RequestResponse>('/signin', { user_id: "test_user", password: "xxx", });
Among them, RequestResponse is the data type to which the returned data is to be parsed, as follows:
export interface RequestResponse { data: any; message: string; resultCode: number; }
In this way, the result is the result of the network request and can be judged and processed.
2. Basic Axios packaging usage:
Axios is simply encapsulated so that multiple network requests can use unified header and other configurations.
Create a new tool class and encapsulate it:
import Axios, { AxiosRequestConfig, AxiosError, AxiosInstance, AxiosResponse } from 'axios'; export const BASE_URL = ""; export const axiosApi = (): AxiosInstance => { const instance = ({ baseURL: BASE_URL, headers: { 'Content-Type': 'application/json', Authorization: `${getAccessToken()}`, }, }); return instance; } const getAccessToken = () => { // Get the local saved token here return xxxxx }
Then the use is as follows:
const response = await axiosApi().post<RequestResponse>('/signin', { user_id: "test_user", password: "xxx", });
3. Usage of adding interceptors
Now we want to add another function, that is, when adjusting the interface, the token is transmitted in the header, but sometimes the interface will fail when the token expires. We want to add unified processing to the encapsulation place. If the token expires, refresh the token and then adjust the interface.
The data format and analysis method of token are known as follows:
import * as crypto from 'crypto'; import * as jwt from "jsonwebtoken"; export interface TokenData { userid: string; exp: number; iat: number; } export const decodeJWT = function (token: string): TokenData { if (!token) { return null; } const decoded = (token, { complete: true }); return decoded?.payload; };
How to refresh the token in a unified manner? Interceptors can be added for processing. Change the Axios package and add an interceptor:
export const axiosApi = (): AxiosInstance => { const instance = ({ baseURL: BASE_URL, headers: { 'Content-Type': 'application/json', Authorization: `${getAccessToken()}`, }, }); // Add an interceptor ( config => { return refreshToken(config); }, err => { return (err) } ) return instance; } // How to refresh the tokenconst refreshToken = async (config: AxiosRequestConfig) => { const oldToken = getAccessToken(); if (!oldToken) { //If there is no token locally, that is, there is no login, then there is no need to refresh the token return config; } const tokenData = decodeJWT(oldToken);//Analyze the token and get the expiration time information contained in the token const currentTimeSeconds = new Date().getTime()/1000; if (tokenData && > currentTimeSeconds) { return config; // The time in the token data is larger than the current time, which means that the expiration time has not reached, so there is no need to refresh it. } // Below is the logic of refreshing the token, here is to adjust the API to obtain a new token const response = await signInRefreshToken(tokenData?.userid); if (response && == 200) { const { token, refresh_token } = ?.data; // Save the refreshed token storeAccessToken(token); // Set a new token for the API's header = token; } return config; }
After adding an interceptor in this way, if the token has not expired, the network request will be made directly; if the token expires, the interface will be adjusted to refresh the token, and then set a new token for the header and then make a network request.
4. Notes:
One thing to note is that when applying it in practice, you should pay attention to:
1. If the interface is adjusted when refreshing the token, the network request tool used cannot also use this encapsulated tool, otherwise it will fall into an infinite loop and you can use a simple unencapsulated method to request.
2. The method used in this example is to refresh the token before making a request. You can also use the method of first regulating the network request, if the interface returns an error code that indicates that the token expires, refresh the token and then re-request.
This is the article about the implementation method of adding interceptor refresh tokens in Vue. For more related content related to Axios adding interceptor refresh tokens, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!