In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article will explain in detail how to add interceptors to refresh token in Axios in vue. The editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.
Axios is a network front-end request framework. The basic usage is as follows:
1. Basic usage of Axios: const response = await Axios.create ({baseURL: "https://test.api.com", headers: {'Content-Type':' application/json',},}). Post ('/ signin', {user_id:" test_user ", password:" xxx " })
Where RequestResponse is the data type to be parsed, as shown below:
Export interface RequestResponse {data: any; message: string; resultCode: number;}
In this way, the resulting response is the result of the network request and can be judged and processed.
2. Basic encapsulation usage of Axios:
The Axios is simply encapsulated so that multiple network requests can be configured with a unified header.
Create a new tool class and encapsulate it:
Import Axios, {AxiosRequestConfig, AxiosError, AxiosInstance, AxiosResponse} from 'axios'; export const BASE_URL = "https://test.api.com"; export const axiosApi = (): AxiosInstance = > {const instance = Axios.create ({baseURL: BASE_URL, headers: {' Content-Type': 'application/json', Authorization: `${getAccessToken ()}`,},}); return instance } const getAccessToken = () = > {/ / get the locally saved token return xxxxx} here
Then the place to use is as follows:
Const response = await axiosApi () .post ('/ signin', {user_id: "test_user", password: "xxx",}); 3. Add the usage of interceptor
Now we want to add another feature, that is, when adjusting the interface, token is passed in the header, but sometimes the interface will return a failure when the token expires. We want to add unified processing in the encapsulation. If the token expires, refresh the token, and then adjust the interface.
The data format and parsing 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 = jwt.decode (token, {complete: true}); return decoded?.payload;}
How to refresh token uniformly? You can add interceptors for processing. Change the encapsulation of Axios and add an interceptor:
Export const axiosApi = (): AxiosInstance = > {const instance = Axios.create ({baseURL: BASE_URL, headers: {'Content-Type':' application/json', Authorization: `${getAccessToken ()}`,},}); / / add interceptor instance.interceptors.request.use (config = > {return refreshToken (config);}, err = > {return Promise.reject (err)}) return instance } / / refresh token method const refreshToken = async (config: AxiosRequestConfig) = > {const oldToken = getAccessToken (); if (! oldToken) {/ / if there is no local token, that is, no login, then there is no need to refresh token return config;} const tokenData = decodeJWT (oldToken); / / parse token to get the expiration time information const currentTimeSeconds = new Date (). GetTime () / 1000; if (tokenData & tokenData.exp > currentTimeSeconds) {return config / / the time in the token data is larger than the current time, that is, there is no need to refresh} / / the following is the logic of refreshing token, here is calling API to get a new token const response = await signInRefreshToken (tokenData?.userid); if (response & & response.status = = 200) {const {token, refresh_token} = response.data?.data; / / Save the refreshed token storeAccessToken (token) / / set the new token config.headers.Authorization = token;} return config;} to the header of API
After adding the interceptor in this way, if the token does not expire, the network request will be made directly; if the token expires, it will call the API to refresh the token, and then set a new token to the header to make the network request.
4. Note:
One thing to note is that in practical application, we should pay attention to:
1. If you adjust the interface when refreshing token, the network request tool used cannot also use this encapsulated tool, otherwise it will fall into an infinite loop and can be requested in a simple unencapsulated way.
two。 The method used in this example is to refresh the token before making the request. You can also use the method of calling the network request first, and if the error code returned by the API indicates that the token has expired, refresh the token and then request it again.
This is the end of this article on "how to add interceptors to refresh token in vue". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.