import React, { useContext, useEffect } from "react";
import axios from "axios";
export const AjaxContext = React.createContext();
export const useAjax = () => useContext(AjaxContext);
const instance = axios.create({
timeout: 5000
});
export function AjaxProvider({ children }) {
useEffect(() => {
const onReq = config => {
config.headers["Authorization"] = localStorage.getItem("token");
return config;
};
const onErr = err => Promise.reject(err);
const flag = instance.interceptors.request.use(onReq, onErr);
return () => instance.interceptors.request.eject(flag);
});
useEffect(() => {
const onRes = res => res;
const onErr = err => {
if (err.response) {
const { status } = err.response;
if (status === 401) {
console.log("捕获到了!");
}
}
return Promise.reject(err);
};
const flag = instance.interceptors.response.use(onRes, onErr);
return () => instance.interceptors.response.eject(flag);
});
const ajax = {
get: path => instance.get(path),
post: (path, data) =>
instance.post(path, data),
put: (path, data) => instance.put(path, data),
delete: path => instance.delete(path)
};
return <AjaxContext.Provider value={ajax} children={children} />;
}