我在我的 react 应用程序中使用 axios 拦截器时遇到问题。我想在我的 react 应用程序中只放置一次 header token 。所以这就是为什么我把它放在拦截器中。同时,我也希望只有一个声明来获取错误。所以我不需要在每一页都显示错误。我想知道我在下面的代码中是否正确使用了它?有没有办法可以缩短它,因为我为响应和请求声明了两次?
export function getAxiosInstance() {
if (axiosInstance === null) {
axiosInstance = axios.create({
baseURL: API_URL,
});
}
axiosInstance.interceptors.request.use(
(config) => {
if (config.baseURL === API_URL && !config.headers.Authorization) {
const token = store.getState().auth.access_token;
if (token) {
config.headers.Authorization = `Bearer ${token}`;
console.log(config);
}
}
return config;
},
(error) => {
console.log(error);
store.dispatch(setAPIErrorMessage(error.message));
return Promise.reject(error);
}
);
axiosInstance.interceptors.response.use(
(config) => {
if (config.baseURL === API_URL && !config.headers.Authorization) {
const token = store.getState().auth.access_token;
if (token) {
config.headers.Authorization = `Bearer ${token}`;
console.log(config);
}
}
return config;
},
(error) => {
console.log(error);
store.dispatch(setAPIErrorMessage(error.message));
return Promise.reject(error);
}
);
return axiosInstance;
}
最佳答案
您不需要在interceptors.response 中设置授权 header ,您只需要在请求拦截器中设置。
您可以在闭包函数中声明您的错误处理(使用 Action 调度)以避免重复自己。
我还建议避免直接在 axios 实例中处理错误。您可以使用 https://github.com/reduxjs/redux-thunk 定义异步 redux 操作,并在 redux 级别处理网络错误(使用 fetchBegin、fetchSuccess、fetchFailure 操作模式)。然后 axios setup 和 redux setup 就不再耦合了,这将允许您将来更改这些工具。
关于javascript - ReactJS Axios 拦截器响应/请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62234869/