1. 程式人生 > 其它 >封裝axios請求

封裝axios請求

import axios from 'axios'
import router from '@/router'
axios.defaults.baseURL = system.requestBaseUrl; // 配置axios請求的地址
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.crossDomain = true;
// axios.defaults.withCredentials = true;  //設定cross跨域 並設定訪問許可權 允許跨域攜帶cookie資訊
axios.defaults.headers.common['Authorization'] = ''; // 設定請求頭為 Authorization
// 請求攔截器
axios.interceptors.request.use(
  config => {
    //驗證登入,並將token放入header
    let url = config.url;
    // console.log('url+======'+url)
    var token = sessionStorage.getItem('token');
    if (url == '/user/sendMsgCode') {
      token = 'token';
    }
    if (!token) { //未登入
      //進入登入頁
      if (sessionStorage.getItem('uname')) {
        sessionStorage.clear()
        Modal.error({
          title: '登入失效或請求失敗!',
          content: '',
          onOk() {
            router.push('/login');
            location.reload(); //強制重新整理
          }
        });
        return
      }
      router.push('/login');
    }
    // console.log(config);
    config.headers['token'] = token;

    return config;
  },
  error => {
    return Promise.error(error);
  }
);

axios.interceptors.response.use(
  response => {
    // console.log('response',response);
    // 否則的話丟擲錯誤
    if (response.status === 200) { //
      if (response.headers['token']) { //重新整理token
        // console.log(response.headers['token']);
        sessionStorage.setItem('token', response.headers['token']);
      }
      if (response.headers['verifyCode']) { //驗證碼
        sessionStorage.setItem('verifyCode', response.headers['verifyCode']);
      }
      return Promise.resolve(response);
    } else {
      return Promise.reject(response);
    }
  },
  error => {
    if (error.response && error.response.status) {
      switch (error.response.status) {
        case 401:
          //刪除token
          sessionStorage.removeItem('token');
          let path = router.history.current.path;
          console.log('path', path)
          if (path != '/login') { //登入頁和初次進首頁不需要確認提示
            if (path == '/') { //直接進首頁
              router.push('/login');
            } else {
              toLogin();
            }
          }
          break;

        case 403:
          // vant.Toast.fail("登入過期,請關閉重新進入。");
          // 清除token
          break;

          // 404請求不存在
        case 404:
          // vant.Toast.fail("您訪問的網頁不存在。");
          break;
          // 其他錯誤,直接丟擲錯誤提示
        default:
          // vant.Toast.fail(error.response.data.message);
      }
      return Promise.reject(error.response);

    } else { //未知異常
      if (error == 'Error: Network Error') { //網路請求失敗
        let path = router.history.current.path;
        if (path != '/login') { //登入頁和初次進首頁不需要確認提示
          Modal.error({
            title: '登入失效或請求失敗!',
            content: '',
            onOk() {
              router.push('/login');
              location.reload(); //強制重新整理
            }
          });
        }
      }
    }
  });

axios.$get = function (url, params) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params
    }, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
    }).then(res => {
      resolve(res.data);
    }).catch(err => {
      reject(err.data)
    })
  })
}
axios.$downLoad = function (url, params) {
  return new Promise((resolve, reject) => {
    axios({
      url: url,
      params: params,
      method: 'get',
      responseType: 'blob'
    }).then(res => {
      resolve(res.data);
    }).catch(err => {
      reject(err.data)
    })
  })
}
// 用於獲得頭部傳過來的檔名資訊
axios.$downLoad1 = function (url, params) {
  return new Promise((resolve, reject) => {
    axios({
      url: url,
      params: params,
      method: 'get',
      responseType: 'blob'
    }).then(res => {
      resolve(res);
    }).catch(err => {
      reject(err)
    })
  })
}
axios.$delete = function (url, params) {
  return new Promise((resolve, reject) => {
    axios.delete(url, {
      params: params
    }, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
    }).then(res => {
      resolve(res.data);
    }).catch(err => {
      reject(err.data)
    })
  })
}
axios.$post = function (url, params, headers_) {
  var headers = headers_ ? {
    'Content-Type': 'application/x-www-form-urlencoded'
  } : headers_;
  return new Promise((resolve, reject) => {
    axios.post(url, QS.stringify(params), {
        headers: headers,
      }).then(res => {
        resolve(res.data);
      })
      .catch(err => {
        reject(err.data)
      })
  })
}
axios.$post1 = function (url, params, headers_) {
  var headers = headers_ ? {
    'Content-Type': 'application/x-www-form-urlencoded'
  } : headers_;
  return new Promise((resolve, reject) => {
    axios.post(url, (params), {
        headers: headers,
      }).then(res => {
        resolve(res.data);
      })
      .catch(err => {
        reject(err.data)
      })
  })
}
axios.$put = (url, params) => {
  var headers = {
    'Content-Type': 'application/x-www-form-urlencoded'
  };
  return new Promise((resolve, reject) => {
    axios.put(url, util.transformFormData(params), {
        headers: headers,
      }).then(res => {
        resolve(res.data);
      })
      .catch(err => {
        reject(err.data)
      })
  })
}
axios.$postExport = function (url, parameter) {
  return axios({
    url: url,
    data: parameter,
    method: 'post',
    responseType: 'blob'
  })

}
export default axios