vue中Axios添加攔截器刷新token的實(shí)現(xiàn)方法
Axios是一款網(wǎng)絡(luò)前端請(qǐng)求框架,基本用法如下:
1. Axios基本用法:
const response = await Axios.create({
baseURL: "https://test.api.com",
headers: {
'Content-Type': 'application/json',
},
}).post<RequestResponse>('/signin', {
user_id: "test_user",
password: "xxx",
});
其中,RequestResponse是返回的數(shù)據(jù)要解析為的數(shù)據(jù)類(lèi)型,如下:
export interface RequestResponse {
data: any;
message: string;
resultCode: number;
}
這樣,得到的response就是網(wǎng)絡(luò)請(qǐng)求的結(jié)果,可以進(jìn)行判斷處理。
2. Axios基本封裝用法:
對(duì)Axios進(jìn)行簡(jiǎn)單的封裝,使得多個(gè)網(wǎng)絡(luò)請(qǐng)求可以使用統(tǒng)一的header等配置。
新建一個(gè)工具類(lèi),進(jìn)行封裝:
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 = () => {
? ? // 這里獲取本地保存的token
? ? return xxxxx
}然后使用的地方是這樣:
const response = await axiosApi().post<RequestResponse>('/signin', {
user_id: "test_user",
password: "xxx",
});
3. 添加攔截器的用法
現(xiàn)在我們想再增加個(gè)功能,就是調(diào)接口時(shí),header里傳了token,但是有時(shí)候token過(guò)期了接口就會(huì)返回失敗,我們想在封裝的地方添加統(tǒng)一處理,如果token過(guò)期就刷新token,然后再調(diào)接口。
其中token的數(shù)據(jù)格式及解析方法已知如下:
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;
};如何統(tǒng)一刷新token呢?可以添加攔截器進(jìn)行處理。把對(duì)Axios的封裝再改下,添加攔截器:
export const axiosApi = (): AxiosInstance => {
? const instance = Axios.create({
? ? baseURL: BASE_URL,
? ? headers: {
? ? ? ?'Content-Type': 'application/json',
? ? ? ?Authorization: `${getAccessToken()}`,
? ? },
? });
??
? // 添加攔截器
? instance.interceptors.request.use(
? ? config => {
? ? ? return refreshToken(config);
? ? },
? ? err => {
? ? ? return Promise.reject(err)
? ? }
? )
? return instance;
}
?
// 刷新token的方法
const refreshToken = async (config: AxiosRequestConfig) => {
? const oldToken = getAccessToken();
? if (!oldToken) { //如果本地沒(méi)有token,也就是沒(méi)登錄,那就不用刷新token
? ? return config;
? }
?
? const tokenData = decodeJWT(oldToken);//解析token,得到token里包含的過(guò)期時(shí)間信息
? const currentTimeSeconds = new Date().getTime()/1000;
?
? if (tokenData && tokenData.exp > currentTimeSeconds) {
? ? return config; // token數(shù)據(jù)里的時(shí)間比當(dāng)前時(shí)間大,也就是沒(méi)到過(guò)期時(shí)間,那也不用刷新
? }
?
? // 下面是刷新token的邏輯,這里是調(diào)API獲取新的token
? const response = await signInRefreshToken(tokenData?.userid);
? if (response && response.status == 200) {
? ? const { token, refresh_token } = response.data?.data;
? ? // 保存刷新后的token
? ? storeAccessToken(token);
? ? // 給API的header設(shè)置新的token
? ? config.headers.Authorization = token;
? }
? return config;
}經(jīng)過(guò)這樣添加了攔截器,如果token沒(méi)過(guò)期,就直接進(jìn)行網(wǎng)絡(luò)請(qǐng)求;如果token過(guò)期了,那就會(huì)調(diào)接口刷新token,然后給header設(shè)置新的token再進(jìn)行網(wǎng)絡(luò)請(qǐng)求。
4. 注意事項(xiàng):
要注意的一點(diǎn)是,實(shí)際應(yīng)用時(shí),要注意:
1.刷新token時(shí)如果調(diào)接口,所使用的網(wǎng)絡(luò)請(qǐng)求工具不能也使用這個(gè)封裝的工具,否則就會(huì)陷入無(wú)限循環(huán),可以使用簡(jiǎn)單未封裝的方式請(qǐng)求。
2.本例使用的方法,是進(jìn)行請(qǐng)求前刷新token。也可以使用先調(diào)網(wǎng)絡(luò)請(qǐng)求,如果接口返回錯(cuò)誤碼表示token過(guò)期,則刷新token,再重新請(qǐng)求的方式。
到此這篇關(guān)于vue中Axios添加攔截器刷新token的實(shí)現(xiàn)方法的文章就介紹到這了,更多相關(guān)Axios添加攔截器刷新token內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue基礎(chǔ)知識(shí)--axios合并請(qǐng)求和slot
這篇文章主要介紹了vue中的axios和slot,文中代碼非常詳細(xì),對(duì)大家的工作學(xué)習(xí)有所幫助,感興趣的朋友可以參考下2020-06-06
vue-quill-editor的使用及個(gè)性化定制操作
這篇文章主要介紹了vue-quill-editor的使用及個(gè)性化定制操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-08-08
nuxt 服務(wù)器渲染動(dòng)態(tài)設(shè)置 title和seo關(guān)鍵字的操作
這篇文章主要介紹了nuxt 服務(wù)器渲染動(dòng)態(tài)設(shè)置 title和seo關(guān)鍵字的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-11-11
Vue頁(yè)面跳轉(zhuǎn)動(dòng)畫(huà)效果的實(shí)現(xiàn)方法
百度了好久都沒(méi)辦法實(shí)現(xiàn)vue中一個(gè)頁(yè)面跳到另一個(gè)頁(yè)面,甚至到google上搜索也是沒(méi)辦法的,最終還是找了高人親自指導(dǎo),所以下面這篇文章主要給大家介紹了關(guān)于Vue頁(yè)面跳轉(zhuǎn)動(dòng)畫(huà)效果的實(shí)現(xiàn)方法,需要的朋友可以參考下2018-09-09
簡(jiǎn)單理解vue中實(shí)例屬性vm.$els
這篇文章主要幫助大家簡(jiǎn)單理解vue中實(shí)例屬性vm.$els,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-12-12
IDEA創(chuàng)建Vue項(xiàng)目的兩種方式總結(jié)
這篇文章主要介紹了IDEA創(chuàng)建Vue項(xiàng)目的兩種方式總結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。2023-04-04
Vue利用canvas實(shí)現(xiàn)移動(dòng)端手寫(xiě)板的方法
本篇文章主要介紹了Vue利用canvas實(shí)現(xiàn)移動(dòng)端手寫(xiě)板的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-05-05
前端Vue3項(xiàng)目打包成Docker鏡像運(yùn)行的詳細(xì)步驟
將Vue3項(xiàng)目打包、編寫(xiě)Dockerfile、構(gòu)建Docker鏡像和運(yùn)行容器是部署Vue3項(xiàng)目到Docker的主要步驟,這篇文章主要介紹了前端Vue3項(xiàng)目打包成Docker鏡像運(yùn)行的詳細(xì)步驟,需要的朋友可以參考下2024-09-09

