axios 拦截器
简介
axios里一般常用的有两种拦截器:请求拦截器、响应拦截器。(自己的学习笔记)
1. 请求拦截器
请求前拦截,可以携带token等数据传给后端
2. 响应拦截器
对响应结果进行解析,统一处理
3. 创建axio实例
const http = axios.create({
timeout: 1000 * 10,
headers: {
"Content-Type": "application/json;charset=utf-8",
"Access-Control-Allow-Origin": "*",
},
});
4. axios请求拦截
http.interceptors.request.use(
// 可以在这里配置token等请求信息
(config)=>{},
(error)=>{}
);
5. axios 响应拦截
http.interceptors.response.use(
// 可以对返回信息进行统一处理
(config)=>{},
(error)=>{}
);
6. axios 请求拦截案例
import axios from "axios";
const baseUrl = process.env.REACT_APP_BASE_URL;
axios.defaults.baseURL = baseUrl;
axios.defaults.withCredentials = true;
const pending = {};
const allPendingRequestsRecord = [];
// axios 的创建
const http = axios.create({
timeout: 1000 * 10,
headers: {
"Content-Type": "application/json;charset=utf-8",
"Access-Control-Allow-Origin": "*",
},
});
// 取消请求的方法
const removeAllPendingRequestsRecord = () => {
allPendingRequestsRecord &&
allPendingRequestsRecord.forEach((func) => {
// cancel the request 取消请求
func("cancel the request");
});
// remove all log 清掉已经取消请求的数据
allPendingRequestsRecord.splice(0);
};
// 调用取消请求的方法
const getConfirmation = () => {
removeAllPendingRequestsRecord();
};
// request interceptors 请求拦截
http.interceptors.request.use(
(config) => {
const token = localStorage.getItem("token") || "";
config.headers["AUTH-TOKEN"] = token;
// save requset,for remove request 存储请求
let reqData = "";
if (config.method === "get") {
reqData = config.url + config.method + JSON.stringify(config.params);
} else {
reqData = config.url + config.method + JSON.stringify(config.data);
}
config.cancelToken = new axios.CancelToken((c) => {
pending[reqData] = c;
allPendingRequestsRecord.push(c);
});
return config;
},
(error) => Promise.reject(error)
);
// response interceptors response 拦截
http.interceptors.response.use(
(res) => {
if (res?.data?.code === 200) {
return res?.data;
} else {
return Promise.reject();
}
},
() => {
return Promise.reject();
}
);
export default http;
export { getConfirmation };