vue+axios 攔截器實(shí)現(xiàn)統(tǒng)一token的案例
需求
要想統(tǒng)一處理所有http請(qǐng)求和響應(yīng),就得用上 axios 的攔截器。通過(guò)配置 http response inteceptor ,當(dāng)后端接口返回 401 Unauthorized(未授權(quán)) ,讓用戶重新登錄。
通過(guò)這個(gè)項(xiàng)目學(xué)習(xí)如何實(shí)現(xiàn)一個(gè)前端項(xiàng)目中所需要的 登錄及攔截、登出、token失效的攔截及對(duì)應(yīng) axios 攔截器的使用。
代碼如下:
const instance = axios.create({ baseURL: 'http://www.laravel5.5.com/api/', timeout: 10000, }); //POST傳參序列化(添加請(qǐng)求攔截器) // 在發(fā)送請(qǐng)求之前做某件事 instance.interceptors.request.use(config => { // // 設(shè)置以 form 表單的形式提交參數(shù),如果以 JSON 的形式提交表單,可忽略 if(config.method === 'post'){ // JSON 轉(zhuǎn)換為 FormData const formData = new FormData(); Object.keys(config.data).forEach(key => formData.append(key, config.data[key])) config.data = formData } // 下面會(huì)說(shuō)在什么時(shí)候存儲(chǔ) token if (localStorage.token) { config.headers['Authorization'] = localStorage.token; config.headers['Accept'] = 'application/json'; // config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'; // store.dispatch('logined', localStorage.token) } return config },error =>{ alert("錯(cuò)誤的傳參", 'fail') return Promise.reject(error) }) // 自定義的 axios 響應(yīng)攔截器 instance.interceptors.response.use((response) => { // 判斷一下響應(yīng)中是否有 token,如果有就直接使用此 token 替換掉本地的 token。你可以根據(jù)你的業(yè)務(wù)需求自己編寫更新 token 的邏輯 var token = response.headers.authorization; if (token) { // 如果 header 中存在 token,那么觸發(fā) refreshToken 方法,替換本地的 token axios.defaults.headers.common['Authorization'] = token; } return response }, (error) => { if (error.response) { switch (error.response.status) { case 401: // 這里寫清除token的代碼 router.replace({ path: 'login', query: {redirect: router.currentRoute.fullPath}//登錄成功后跳入瀏覽的當(dāng)前頁(yè)面 }) } } return Promise.reject(error) }); Vue.http = Vue.prototype.$http = instance;
簡(jiǎn)單的分享一下自己的代碼;這是本人結(jié)合JWT-Auth定制的axios攔截,
1.根據(jù)用戶是否登陸,查看用戶請(qǐng)求頭是否攜帶token
2.根據(jù)判斷后臺(tái)響應(yīng)值headers是否攜帶Authorization值,如果存在,刷新Token
3.如果用戶授權(quán)失敗,直接跳至登陸頁(yè)面
補(bǔ)充知識(shí):vue封裝axios(統(tǒng)一添加請(qǐng)求參數(shù),如token useId等)
main.js中:
import axios from 'axios' import VueAxios from 'vue-axios' import qs from 'qs'; Vue.prototype.$qs = qs; //請(qǐng)求的攔截器 /*axios.defaults.transformRequest=[function(data){ return qs.stringify(data); }];*/ axios.interceptors.request.use(function(config){ const cl_u_id=localStorage.getItem('cl_u_id'); const appId=localStorage.getItem('appId'); if(config.headers['Content-Type'] == 'multipart/form-data'){ config.data.set('cl_u_id',cl_u_id); config.data.set('appId',appId); return config; } //判斷請(qǐng)求的類型:如果是post請(qǐng)求就把默認(rèn)參數(shù)拼到data里面;如果是get請(qǐng)求就拼到params里面 if(config.method==='post'){ config.data=qs.stringify({ cl_u_id:cl_u_id, appId:appId, ...config.data }) }else if(config.method==='get'){ config.params={ cl_u_id:cl_u_id, appId:appId, ...config.params } } return config; },function(error){ return Promise.reject(error); }) Vue.use(VueAxios, axios)
以上這篇vue+axios 攔截器實(shí)現(xiàn)統(tǒng)一token的案例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
前端實(shí)現(xiàn)Vue組件頁(yè)面跳轉(zhuǎn)的多種方式小結(jié)
這篇文章主要為大家詳細(xì)介紹了前端實(shí)現(xiàn)Vue組件頁(yè)面跳轉(zhuǎn)的多種方式,文中的示例代碼講解詳細(xì),具有一定的參考價(jià)值,有需要的小伙伴可以了解下2024-02-02vue+el使用this.$confirm,不能阻斷代碼往下執(zhí)行的解決
這篇文章主要介紹了vue+el使用this.$confirm,不能阻斷代碼往下執(zhí)行的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09詳解element上傳組件before-remove鉤子問(wèn)題解決
這篇文章主要介紹了詳解element上傳組件before-remove鉤子問(wèn)題解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04Vue中使用Scss實(shí)現(xiàn)配置、切換主題方式
這篇文章主要介紹了Vue中使用Scss實(shí)現(xiàn)配置、切換主題方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03Vue 項(xiàng)目部署到服務(wù)器的問(wèn)題解決方法
本篇文章主要介紹了Vue 項(xiàng)目部署到服務(wù)器的問(wèn)題解決方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-12-12