axios 攔截器的用法

什麼是攔截器

攔截器就是攔截每一次的請求和響應,而後進行相應的處理。請求攔截器,它能夠統一在你發送請求前在請求體里加上token;響應攔截器,是在接受到響應以後進行的一些操做,好比,服務器返回登陸狀態失效,須要從新登陸的時候,就給它跳到登陸頁面;ios

建立 axios 實例
const Axios = axios.create({
    baseURL: HOST, // 請求的域名
    timeout: 10000000000, // 響應超時時間
    responseType: "json",
    withCredentials: true, // 跨域請求是否要攜帶cookie
    headers: {
      'Content-Type': 'application-json/x-www-form-urlencoded;charset=utf-8',
    }
  });
請求攔截器
//在發送請求以前作的一些操做,例如加上token
Axios .interceptors.request.use( config => {  
     // 爲請求頭對象添加 token 驗證的 Authorization 字段
     config.headers.Authorization = window.sessionStorage.getItem('token')
     return config
}, error => {
     //對請求錯誤作些什麼
     return Promise.reject(error)
})
響應攔截器
//接收到響應後要作些什麼,好比跳轉到登陸頁
Axios.interceptors.response.use(response => {
	response => {
    //攔截響應,作統一處理 
    if (response.data.code) {
      switch (response.data.code) {
        case 1002:
          store.state.isLogin = false
          router.replace({
            path: 'login',
            query: {
              redirect: router.currentRoute.fullPath
            }
          })
      }
    }
    return response
}, error => {
     //對響應錯誤作些什麼
     return Promise.reject(error)
})
對每一個請求方式進行封裝
export function requestGet(url, query) {
// 查
    return Axios.get(url, { params: query || {} })
      .then((res) => {
        return Promise.resolve(res.data)
        console.log(res.data);
      })
  }
 
  export function requestPost(url, data) {
  // 改
    return Axios.post(url, data)
      .then((res) => {
        return Promise.resolve(res.data)
      })
  }
  
  export function requestPut(url, data) {
  // 增
    return Axios.put(url, data)
      .then((res) => {
        return Promise.resolve(res.data)
      })
  }
  
  export function requestDelete(url) {
  // 刪
    return Axios.delete(url)
      .then((res) => {
        return Promise.resolve(res.data)
      })
  }
應用

最後把封裝的實例在須要的地方導入就能夠了。json

相關文章
相關標籤/搜索