1:package.json 添加
"proxy": "代理地址"
2 封装axios
创建server.js 添加
import axios from "axios";
import qs from "qs";
import axios from "axios";
import qs from "qs";
//终止axios的fun
let axiosToken = null;
//请求超时时间
//axios.defaults.timeout = 10000;
// axios拦截器
axios.interceptors.request.use(
config => {
// 在发送请求之前做些什么
return config;
},
err => {
return Promise.reject(err);
}
);
axios.interceptors.response.use(
response => {
//请求完成token置空
axiosToken = null;
return response;
},
error => {
//请求完成token置空
axiosToken = null;
//提示信息
if (axios.isCancel(error)) alert(error.message, "center");
else alert("请稍后再试...", "center");
return Promise.reject(error.response.data); // 返回接口返回的错误信息
}
);
class HttpRequest {
get(httpUrl, paramsData, successFun, errorFun) {
axios
.get(httpUrl, paramsData)
.then(function(res) {
successFun(res);
})
.catch(function(err) {
console.log("请求失败! " + err);
});
}
// post请求
post(httpUrl, paramsData, successFun, errorFun) {
let paramsDatas = paramsData;
//转为json
paramsDatas = qs.stringify(paramsDatas);
axios
.post(httpUrl, paramsDatas, {
//终止请求
cancelToken: new axios.CancelToken(function executor(c) {
axiosToken = c;
})
})
.then(res => {
successFun(res);
})
.catch(err => {
console.log(err);
});
}
//终止请求
doCancelToken(msg = "取消") {
if (axiosToken) axiosToken(msg);
}
}
export default new HttpRequest();
3 引入使用 就可以了