vue-axios-二次封装

41次阅读

共计 1311 个字符,预计需要花费 4 分钟才能阅读完成。

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

// 环境的切换
// 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 拦截器
axios.interceptors.request.use(
config => {

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

},
error => {

return Promise.reject(error);

}
);

// 响应拦截器即异常处理
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('错误请求')
      break;
    case 403:
      console.log('拒绝访问')
      break;
    case 404:
      console.log('请求错误, 未找到该资源')
      break;
    case 500:
      console.log('服务器端出错')
      break;
    case 501:
      console.log('网络未实现')
      break;
    case 502:
      console.log('网络错误')
      break;
    default:
      console.log(` 连接错误 ${err.response.status}`)
  }
} else {console.log('连接到服务器失败')
}
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)
      })
  });
}

};

正文完
 0