如何使用React Redux Axios实现令牌自动刷新

时间:2020-02-11 06:02:46

标签: javascript reactjs redux react-redux axios

当用户在某个字段或表单中键入大量信息,然后令牌过期时,会发生这种情况。在这种情况下,用户将丢失所有信息。因此,我们应该实现自动令牌刷新功能

这是中间件配置

const middlewareConfig = {
  interceptors: {
    request: [
      ({ getState, dispatch }, config) => {
        return config;
      },
    ],
    response: [
      {
        error: ({ getState, dispatch, getSourceAction }, error) => {
          if (error.response.status === 401) {
            dispatch(actions.setAuthErrorStatus());
          }
          if (error.response.headers.hasOwnProperty('sso-authenticate')) {
            redirectToLocationUrl(error.response.headers["sso-authenticate"])
          } else if (error.response.config.method === 'get') {
            if (url_config.DEFAULT_CLIENT === 'local_proxy') {
              cancelEventNotification(error);
            }
          }
          return Promise.reject(error);
        },
        success: ({ dispatch }, response) => {
          redirectToLocationUrl(response.headers.location);
          return response;
        },
      },
    ],
  },
  returnRejectedPromiseOnError: false,
};

这是商店创建的文件

import React from 'react';
import { Provider } from 'react-redux';
import { applyMiddleware, createStore } from 'redux';
import { multiClientMiddleware } from 'redux-axios-middleware';
import { composeWithDevTools } from 'redux-devtools-extension';
import reduxThunk from 'redux-thunk';

import { clients } from './middlewares/axiosMiddleware/clients';
import config from './middlewares/axiosMiddleware/config';
import reducers from './reducers';

interface IRootChildren {
  children: JSX.Element;
}

const middlewares = [reduxThunk, multiClientMiddleware(clients, config)];
const store = createStore(reducers, composeWithDevTools(applyMiddleware(...middlewares)));

export default ({ children }: IRootChildren) => {
  return (
    <Provider store={ store }>
      { children }
    </Provider>
  );
};

0 个答案:

没有答案