80 lines
1.9 KiB
JavaScript
80 lines
1.9 KiB
JavaScript
|
import axios from "axios";
|
||
|
const qs = require("qs");
|
||
|
|
||
|
class HttpRequest {
|
||
|
constructor(baseUrl) {
|
||
|
this.baseUrl = baseUrl;
|
||
|
this.queue = {};
|
||
|
}
|
||
|
|
||
|
getInsideConfig() {
|
||
|
const config = {
|
||
|
baseURL: this.baseUrl,
|
||
|
headers: {
|
||
|
"content-type": "application/x-www-form-urlencoded",
|
||
|
},
|
||
|
};
|
||
|
return config;
|
||
|
}
|
||
|
|
||
|
interceptors(instance, url) {
|
||
|
// 请求拦截
|
||
|
instance.interceptors.request.use(
|
||
|
(config) => {
|
||
|
this.queue[url] = true;
|
||
|
if (
|
||
|
config.method === "post" ||
|
||
|
config.method === "POST" ||
|
||
|
config.method.toLocaleUpperCase() === "PATCH"
|
||
|
) {
|
||
|
config.data = qs.stringify({ //转json字符串
|
||
|
// ...info,
|
||
|
...config.data,
|
||
|
});
|
||
|
// config.data = {
|
||
|
// // ...info,
|
||
|
// ...config.data,
|
||
|
// };
|
||
|
} else if (config.method === "get" || config.method === "GET") {
|
||
|
config.params = {
|
||
|
...config.params,
|
||
|
};
|
||
|
}
|
||
|
return config;
|
||
|
},
|
||
|
(error) => {
|
||
|
return Promise.reject(error);
|
||
|
}
|
||
|
);
|
||
|
|
||
|
// 响应拦截
|
||
|
instance.interceptors.response.use(
|
||
|
(res) => {
|
||
|
const { data } = res;
|
||
|
return data;
|
||
|
},
|
||
|
(error) => {
|
||
|
const errorInfo = error.response;
|
||
|
if (!errorInfo) {
|
||
|
// const { request: {status }, config } = JSON.parse(JSON.stringify(error))
|
||
|
// errorInfo = {
|
||
|
// status,
|
||
|
// request: { responseURL: config.url }
|
||
|
// }
|
||
|
}
|
||
|
return Promise.reject(errorInfo);
|
||
|
}
|
||
|
);
|
||
|
}
|
||
|
|
||
|
request(options) {
|
||
|
// 设置超时时间
|
||
|
const instance = axios.create();
|
||
|
instance.defaults.timeout = 30000;
|
||
|
options = Object.assign(this.getInsideConfig(), options);
|
||
|
this.interceptors(instance, options.url);
|
||
|
return instance(options);
|
||
|
}
|
||
|
}
|
||
|
export default HttpRequest;
|