带自定义中间件的Redux授权句柄

问题描述 投票:0回答:1

我需要使我的redux API调用标头集中。我的意思是我需要一个自定义中间件,该中间件在每个api调用之前都可以工作,并从“本地存储”中获取令牌并将其放入当前api调用的标头中。我用Google搜索时发现了一些示例,但我还需要401未经授权的处理。在每个api调用之后,如果我得到401未经授权的响应,则中间件将清除本地存储。感谢您的帮助,谢谢。我发现了以下类似的示例,但在api调用处理401未经授权的情况后,我也需要它。


const authInterceptor = ({ dispatch }) => (next) => (action) => {
  if (action.status === 401) {
    dispatch(actions.removeJwt());
  } else {
    next(action);
  }
};

api redux authorization middleware unauthorized
1个回答
0
投票

您可以通过错误处理来处理4xx响应。例如,如果您使用axios api,则可以使用全局响应处理程序。

axiosInstance.interceptors.response.use(
  response => successHandler(response),
  error => errorHandler(error)
)

有关更多信息:Axios response and error interceptors

© www.soinside.com 2019 - 2024. All rights reserved.