vue axios攔截器介紹

axios的攔截器是一個作用非常大,非常好用的東西。分爲請求攔截器和相應攔截器兩種。
我一般把攔截器寫在main.js裏。

1. 請求攔截器

請求攔截器的作用是在請求發送前進行一些操作,例如在每個請求體里加上token,統一做了處理如果以後要改也非常容易。

axios.interceptors.request.use(function (config) {
    // 在發送請求之前做些什麼,例如加入token(僞代碼,實際根據需求來)
    if(config.method == 'post'){
        if(config.headers['Content-Type'] == 'multipart/form-data'){
          return config;
        }else{
          if(config.data == '') {
            config.data += `token=${token}`
          }else{
            config.data += `&token=${token}`;
          }
    }
    return config;
  }, function (error) {
    // 對請求錯誤做些什麼
    return Promise.reject(error);
  });

2. 響應攔截器

響應攔截器的作用是在接收到響應後進行一些操作,例如在服務器返回登錄狀態失效,需要重新登錄的時候,跳轉到登錄頁。

axios.interceptors.response.use(function (response) {
    // 在接收響應做些什麼,例如跳轉到登錄頁(僞代碼,實際根據需求來)
    if(res.code == 301) {
        router.push('/login')
    }
    return response;
  }, function (error) {
    // 對響應錯誤做點什麼
    return Promise.reject(error);
  });

攔截器真的非常重要非常好用~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章