import axios from "axios";
const baseOptions = {};
const instance = axios.create(baseOptions);
// 用以控制请求的全局状态
const globalParams = {
// 是否统一处理响应,
// 1 ture,则返回响应,并根据http 错误状态码抛错
// 2 false, 将响应或错误直接抛给调用者,调用者自行处理
isUnified: true,
isReturnData: true, // 是否值接返回response.data
isLoading: false, // 是否有 loading 效果
isCheckParams: false, // 检查用户输入是否存在违规内容, 比如 <script> </script> 等
};
// 从 config 向 global 合并属性
// 开发者在传递玩请求参数后边, 追加一个对象类型的参数, 配置相关属性即可
/**
* 示例
const onFinish = async (values) => {
console.log(values);
const res = await req.post('/react/register', values, {
isUnified : false
})
console.log(res);
}
*/
const correspondWithConfig = (config) => {
const keys = Object.keys(globalParams);
keys.forEach((key) => {
if (config.hasOwnProperty(key)) {
globalParams[key] = config[key];
}
});
};
// 参数校验、检查逻辑
const checkParams = config => {
}
const handleConfig = (config) => {
correspondWithConfig(config);
checkParams(config)
};
// 注意查看 config 的属性
instance.interceptors.request.use(
(config) => {
handleConfig(config);
console.log(config);
return config;
},
(error) => {
return Promise.reject(error);
}
);
// 处理约定的业务代码
const handleBussnessCode = data => {
}
// 处理正常响应
const handleResponse = (res) => {
const { isUnified, isLoading, isReturnData } = globalParams;
if(isLoading) {
// close loading
}
if(isUnified) {
if(isReturnData) {
// 统一处理响应
return res.data
}
handleBussnessCode(res.data)
}
return res
};
const handleHTTPStatusCode = e => {
}
// 处理响应错误
const handleResponseError = e => {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
if(e.response) {
handleBussnessCode(e)
}
else if(e.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
}
else {
// Something happened in setting up the request that triggered an Error
}
// 其他错误
return e
}
instance.interceptors.response.use(
response => handleResponse(response),
error => Promise.reject(handleResponseError(error))
);
export default instance;
通用 axios 封装处理,拿来即用
最新推荐文章于 2025-04-25 02:58:45 发布