前端axios请求封装以及拦截器
import axios from "axios";
import QS from "qs";
import { message } from "antd";
import store from "../store";
axios.defaults.timeout = 50000;
axios.defaults.baseURL = "http://xx.xx.xx.xxx:xxxx";
axios.interceptors.request.use(
(config) => {
if (config.url == "/login") {
} else {
let token = store.getState().token;
if(config.isUpload){
config.headers = {
'Content-Type': 'multipart/form-data',
'Authorization': token
}
}else{
config.headers.Authorization = token;
}
}
return config;
},
(err) => {
return Promise.reject(err);
}
);
axios.interceptors.response.use(
(response) => {
if (response.status === 200) {
} else {
message.error("响应不正常");
}
return response;
},
(error) => {
try {
console.log(error);
if (error.response.status === 401) {
message.error(error.response.data.msg);
window.location.href = "/login";
return;
} else {
return;
}
} catch (e) {
console.log(e);
}
}
);
export function getData(url, params) {
return new Promise((resolve, reject) => {
axios
.get(url, { params: params })
.then((response) => {
resolve(response.data);
})
.catch((error) => {
reject(error);
});
});
}
export function postData(url, params, end) {
return new Promise((resolve, reject) => {
axios
.post(url, QS.stringify(params))
.then((response) => {
if (response.status === 200) {
resolve(response.data);
}
})
.catch((error) => {
reject(error);
});
});
}
export function UploadFile(url, data) {
return new Promise((resolve, reject) => {
console.log(data)
axios.post(url, data ,{isUpload : true})
.then((response) => {
resolve(response);
})
.catch((error) => {
reject(error);
});
});
}
export function Postdownload(url, params, responsetype) {
return new Promise((resolve, reject) => {
axios
.post(url, QS.stringify(params))
.then((response) => {
resolve(response);
})
.catch((error) => {
reject(error);
});
});
}