在使用axios的請求攔截器axios.interceptors.request對請求數(shù)據(jù)做處理時,有一個需求就是通過自定義參數(shù)needLogin判斷該請求是否需要驗證登錄信息。需要的話,在請求之前,前端就進(jìn)行一次校驗,避免前端存儲的登錄token已失效情況下任然發(fā)送請求增加后臺負(fù)擔(dān)。
通過【請求攔截器 】axios.interceptors.request.user((config)=>{}) 進(jìn)行攔截判斷是否 needLogin
在main.js設(shè)置攔截器
//main.js
import Vue from 'vue';
import router from './router';
import store from './store';
import axios from 'axios';
import vueAxios from 'vue-axios';
Vue.use(vueAxios, axios);
axios.defaults.timeout = 5000;// 請求超時
axios.defaults.baseURL = process.env.VUE_APP_URL;
// axios.defaults.headers.post['Content-Type'] = 'application/json';
// 添加請求攔截器
axios.interceptors.request.use(function (config) {
// 在發(fā)送請求之前做些什么
//1、判斷是否需要登錄
console.log(`請求【${config.url}】${config.needLogin?'需要':'不需要'}登錄`);
if(config.needLogin){
if(store.state.token){
console.log(`【store.state.token】存在 = ${store.state.token}`);
}else{
console.warn(`【store.state.token】不存在`);
//需要從 localStorage 中重新獲取token,獲取失敗則跳轉(zhuǎn)登錄頁
}
}
//2、將token添加入頭部
if (store.state.token) {
//如果vuex中存儲有用戶token,就把token傳給后端
config.headers.token = `${store.state.token}`;
}
return config;
}, function (error) {
// 對請求錯誤做些什么
return Promise.reject(error);
});
let app = new Vue({
router,
store,
render: h => h(App),
}).$mount('#app');
然后我們調(diào)用axios.request()驗證一下
//list.vue
<script>
export default {
name: 'list',
data(){
return {
list:[],//列表
}
},
created(){
console.log('created');
this.getList();
},
methods:{
getList(){
this.axios.request({
needLogin:true,//這里設(shè)置了needLogin
method:"get",
url:"/test-json/order_list.json",
}).then((response)=>{
// console.log('response',response,arguments);
}).catch((error)=>{
console.log('error',error,arguments);
})
}
},
};
</script>
然后,我們會發(fā)現(xiàn)

找不到.png
為什么config中找不到needLogin?
因為axios對傳入的參數(shù)做了過濾處理,我們需要在過濾白名單數(shù)組中增加我們需要的字段:

新增needlogin.png
最后重新編譯(重啟服務(wù))再試一下:

最后.png