创建utils 配置axios请求 创建request.js 默认导出 一般情况下无需引入
import axios from 'axios';
import qs from 'querystring';
const errorHandle = (status,info)=>{
switch(status){
case 400:
console.log('请求报文中存在语法错误');
break;
case 401:
console.log("未经许可,需要通过HTTP认证");
break;
case 403:
console.log("服务器拒绝该次访问");
break;
case 404:
console.log("访问资源不存在");
break;
case 500:
console.log("服务器在执行请求时发生了错误");
break;
case 503:
console.log("服务器暂时处于超负载或正在进行停机维护");
break;
default:
console.log(info);
}
}
var instance = axios.create({
timeout:5000
})
instance.interceptors.request.use(
config=>{
if(config.method === "post"){
config.data === qs.stringify(config.data)
}
return config
},
error => Promise.reject(error)
);
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
instance.interceptors.response.use(
response=>
response.status === 200 ? Promise.resolve(response) : Promise.resolve(response),
error =>{
const { response } = error;
console.log(response);
if(response){
errorHandle(response.status,response.info);
return Promise.reject(response)
}else{
console.log("请求中断");
}
}
)
export default instance;