Vue Axios secondary packaging

Time:2020-8-1

import axios from ‘axios’;
import QS from ‘qs’;

//Environment switching
// if (process.env.NODE_ENV === ‘development’) {
// axios.defaults.baseURL = ‘http://172.16.70.100:9999/qd’;
// } else if (process.env.NODE_ENV === ‘production’) {
// axios.defaults.baseURL = ‘https://www.production.com’;
// }

axios.defaults.timeout = 5000;
//HTTP request interceptor
axios.interceptors.request.use(
config => {

config.headers = {
  'Content-Type':'application/x-www-form-urlencoded'
}
return config;

},
error => {

return Promise.reject(error);

}
);

//Response interceptor is exception handling
axios.interceptors.response.use(
response => {

if (response.status === 200) {
  return Promise.resolve(response);
} else {
  return Promise.reject(response);
}

},
err => {

if (err && err.response) {
  switch (err.response.status) {
    case 400:
        console.log ('bad request ')
      break;
    case 403:
      console.log ('Access denied ')
      break;
    case 404:
      console.log ('request error, resource not found ')
      break;
    case 500:
      console.log ('server side error ')
      break;
    case 501:
      console.log ('network not implemented ')
      break;
    case 502:
      console.log ('network error ')
      break;
    default:
      console.log (` connection error${ err.response.status >)
  }
} else {
  console.log ('connection to server failed ')
}
return Promise.resolve(err.response)

})

export default {

get(url, params){
  return new Promise((resolve, reject) => {
      axios.get(url,{
        params:params
      }).then(res => {
        resolve(res.data);
      }).catch(err =>{
        reject(err.data);
      })
  })
},
post(url, params) {
  return new Promise((resolve, reject) => {
       axios.post(url, QS.stringify(params))
      .then(res => {
          resolve(res.data);
      })
      .catch(err =>{
          reject(err.data)
      })
  });
}

};