React+JS,请求简易封装
import axios from "axios";
const timeout = 60000; // 请求超时时间和延迟请求超时时间统一设置
const config = {
baseURL: '接口前缀',
timeout,
headers: {
"Content-Type": "application/json",
"Authorization": sessionStorage.getItem("token")
}
};
const instance = axios.create(config);
instance.interceptors.request.use(async (config) => {
if (!config.extraConfig?.tokenRetryCount) {
config.extraConfig = {
tokenRetryCount: 0,
};
}
(config.headers)["Authorization"] = sessionStorage.getItem("token");
return config;
});
/**
* http response 拦截器
*/
instance.interceptors.response.use(
(response) => {
return response.data;
},
async (err) => {
if (axios.isCancel(err)) {
// 取消的请求,不报错
return;
}
if (err.message === "Network Error") {
console.log("Network Error");
return;
}
if (err.message.includes("timeout")) {
return;
}
if (err.response?.status >= 500) {
return;
}
const { data: responseData } = err.response || {};
const { status } = responseData || {};
if (status) {
switch (parseInt(status)) {
case 4001:
break;
default:
break;
}
}
return err.response;
}
);
const get = (url, params, responseType) => {
return instance.get(url, { params, ...responseType });
}
const post = (url, data, config) => {
return instance.post(url, data, config);
}
const del = (url, params) => {
return instance.delete(url, { params });
}
const put = (url, data) => {
return instance.put(url, data);
}
// const upload = (url, data)=> {
// return instance.post(url, data,{headers: {
// 'Content-Type': 'multipart/form-data'
// }});
// }
export { get, post, del, put };
2.api统一接口封装
import { get, post } from './requer.js';
/**
* 获取首页列表
*/
export const logindata = (data) => {
return post('接口后缀', data);
}
页面使用