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

时间:2018-10-23 10:05:09

标签: 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的反应代码

我看到了

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
};

所以我不知道该怎么转:(

解决这个问题

感谢Bruno Paulino的帮助 我用这段代码解决了

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())
});

3 个答案:

答案 0 :(得分:3)

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

有了这些,您可以像这样直接从redux存储分派动作:

// Our data store
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'));

答案 1 :(得分:1)

我也遇到了同样的问题,这是我的解决方案:

  1. 定义axios拦截器并调用redux存储。
import Axios from 'axios';

const interceptor = (store) => {
    Axios.interceptors.request.use(
        (conf) => {
            if(!conf.headers['Authorization']){
                
            }
            console.log(store);
            debugger;
            // you can add some information before send it.
            // conf.headers['Auth'] = 'some token'
            return conf;
        },
        (error) => {
            debugger;
            return Promise.reject(error);
        }
    );
    Axios.interceptors.response.use(
        (next) => {
            debugger;
            return Promise.resolve(next);
        },
        (error) => {
            // You can handle error here and trigger warning message without get in the code inside
            
            debugger;
            return Promise.reject(error);
        }
    );
};
const store = createStore(reducer, enhancer);
interceptor(store);
  1. 将redux存储配置到您的项目中。
  2. 致电axios请求
function getAllCompany(userObject) {

    let headers = { 'Authorization': 'Bearer ' + userObject.accessToken }

    return axios({
        method: 'post',
        url: rootURL + "/getallcompany",
        data: { },
        headers: headers
    }).then(handleResponse).catch(handleError);
}

答案 2 :(得分:0)

我有同样的问题。 我想说,解决该问题的关键是在我导出axios实例的文件之外添加一个拦截器。