ReactJS axios 拦截器如何调度注销操作

标签 reactjs axios

如何调度注销操作 如果状态为 401/403

使用此代码

import axios from "axios";
import { Storage } from "./utils/storage";
const instance = axios.create({
  baseURL: process.env.API_URL,
  timeout: 3000
});

const onRequestSuccess = config => {
  console.log("request success", config);
  const token = Storage.local.get("auth");
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
};
const onRequestFail = error => {
  console.log("request error", error);
  return Promise.reject(error);
};
instance.interceptors.request.use(onRequestSuccess, onRequestFail);

const onResponseSuccess = response => {
  console.log("response success", response);
  return response;
};
const onResponseFail = error => {
  console.log("response error", error);
  const status = error.status || error.response.status;
  if (status === 403 || status === 401) {
    //dispatch action logout
  }
  return Promise.reject(error);
};
instance.interceptors.response.use(onResponseSuccess, onResponseFail);

export default instance;

更新

我偷看了 jhipster react 代码

我看到了

const actions = bindActionCreators({ logOut }, store.dispatch);
setupAxiosInterceptors(() => actions.logOut());

但我想使用像这样的实例

import axios from "../../../axios";
import API_URLS from "../../../constants/api";

const accountUrl = API_URLS.account;

const account = data => {
  return axios.post(accountUrl, data).then(response => {
    return response.data;
  });
};

export const Provider = {
  account
};

所以我不知道该转向哪个方向:(

解决问题

感谢布鲁诺·保利诺的帮助 我用这段代码解决了

import axios from "./axios";
import { Storage } from "./utils/storage";

const setupAxiosInterceptors = onUnauthenticated => {
  const onRequestSuccess = config => {
    console.log("request success", config);
    const token = Storage.local.get("auth");
    if (token) {
      config.headers.Authorization = `${token.token}`;
    }
    return config;
  };
  const onRequestFail = error => {
    console.log("request error", error);
    return Promise.reject(error);
  };
  axios.interceptors.request.use(onRequestSuccess, onRequestFail);

  const onResponseSuccess = response => {
    console.log("response success", response);
    return response;
  };
  const onResponseFail = error => {
    console.log("response error", error);
    const status = error.status || error.response.status;
    if (status === 403 || status === 401) {
      onUnauthenticated();
    }
    return Promise.reject(error);
  };
  axios.interceptors.response.use(onResponseSuccess, onResponseFail);
};
export default setupAxiosInterceptors;


const {dispatch} = store;
setupAxiosInterceptors(()=>{
  dispatch(authLogout())
});

最佳答案

您可以将此拦截器代码包含在您可以直接访问 redux 存储的同一位置。也许在您创建 redux 存储 (index.js) 的文件中?

完成后,您可以直接从 redux 存储中分派(dispatch)操作,如下所示:

import reduxStore from './store';

import App from './components/App';

const router = (
  <Provider store={reduxStore}>
    <Router>
      <Route path="/" component={App}/>
    </Router>
  </Provider>
);

/** Intercept any unauthorized request.
* dispatch logout action accordingly **/
const UNAUTHORIZED = 401;
const {dispatch} = reduxStore; // direct access to redux store.
axios.interceptors.response.use(
  response => response,
  error => {
    const {status} = error.response;
    if (status === UNAUTHORIZED) {
      dispatch(userSignOut());
    }
   return Promise.reject(error);
 }
);

render(router, document.getElementById('app-root'));

关于ReactJS axios 拦截器如何调度注销操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52946376/

相关文章:

ajax - 调度执行 AJAX 请求的操作时出现无限循环 - ReactJS、Redux、Redux-saga

reactjs - Tailwind - 条件类渲染

reactjs - reducer Action 不动态更新

javascript - 如何在 React 中使用外部 api

go - axios 不发送 POST 到 golang api

javascript - 未捕获的语法错误 : Unexpected token < occurring when deploying

vue.js - 使用 Axios 进行 POST 到 DRF

javascript - axios没有发出请求,没有结果,没有错误

javascript - Vue.js中后端API数据值变化如何自动更新前端?

reactjs - create-react-app 中的 public/manifest.json 文件是什么?