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 input標(biāo)簽通用指令校驗(yàn)的實(shí)現(xiàn)
這篇文章主要介紹了vue input標(biāo)簽通用指令校驗(yàn)的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11vue.js 底部導(dǎo)航欄 一級(jí)路由顯示 子路由不顯示的解決方法
下面小編就為大家分享一篇vue.js 底部導(dǎo)航欄 一級(jí)路由顯示 子路由不顯示的解決方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-03-03vue監(jiān)聽(tīng)滾動(dòng)條頁(yè)面滾動(dòng)動(dòng)畫(huà)示例代碼
Vue是一套用于構(gòu)建用戶界面的漸進(jìn)式框架,與其它大型框架不同的是,Vue?被設(shè)計(jì)為可以自底向上逐層應(yīng)用,下面這篇文章主要給大家介紹了關(guān)于vue監(jiān)聽(tīng)滾動(dòng)條頁(yè)面滾動(dòng)動(dòng)畫(huà)的相關(guān)資料,需要的朋友可以參考下2023-06-06