axios.interceptors.request 支持config自定義參數(shù)

在使用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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 夜鶯2517閱讀 128,087評論 1 9
  • 版本:ios 1.2.1 亮點(diǎn): 1.app角標(biāo)可以實時更新天氣溫度或選擇空氣質(zhì)量,建議處女座就不要選了,不然老想...
    我就是沉沉閱讀 7,361評論 1 6
  • 我是黑夜里大雨紛飛的人啊 1 “又到一年六月,有人笑有人哭,有人歡樂有人憂愁,有人驚喜有人失落,有的覺得收獲滿滿有...
    陌忘宇閱讀 8,814評論 28 54
  • 兔子雖然是枚小碩 但學(xué)校的碩士四人寢不夠 就被分到了博士樓里 兩人一間 在學(xué)校的最西邊 靠山 兔子的室友身體不好 ...
    待業(yè)的兔子閱讀 2,759評論 2 9

友情鏈接更多精彩內(nèi)容