Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/421.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为过期会话创建redux中间件重试函数_Javascript_Reactjs_Redux - Fatal编程技术网

Javascript 为过期会话创建redux中间件重试函数

Javascript 为过期会话创建redux中间件重试函数,javascript,reactjs,redux,Javascript,Reactjs,Redux,在我的应用程序中,我通过api中间件运行每个请求。我正在尝试创建一个中间件重试函数,当发生具有的请求并且令牌过期时。以下是我当前的API中间件: const apiMiddleware = ({ dispatch }) => next => action => { next(action); // creating request data and params const retryRequest = () => { // refresh toke

在我的应用程序中,我通过api中间件运行每个请求。我正在尝试创建一个中间件重试函数,当发生具有的请求并且令牌过期时。以下是我当前的API中间件:

const apiMiddleware = ({ dispatch }) => next => action => {
  next(action);
  // creating request data and params

  const retryRequest = () => {
    // refresh tokens with method: dispatch(getTokens());
    // retry initial request
  };

  axios({
    method,
    url,
    headers,
    [dataOrParams]: data,
  })
    .then(({ data: apiData }) => {
      dispatch(onSuccess(apiData));
    })
    .catch(error => {
      if (withToken && error.response.status === 401) {
        retryRequest();
      }
      return dispatch(apiError(label, error));
    })
};

export default apiMiddleware;
当我调用
retryRequest()
方法时,
getTokens()
请求启动,但同时启动初始请求,并且Redux尚未使用新的刷新令牌更新,请求再次失败,因为
getTokens()
未完成


我知道我做得不对,还有什么其他的解决办法可以尝试?因此,首先调用并完成请求
getTokens()
,然后才能继续初始请求。

如果可以使retryRequest()和catch函数异步,则可以使用

if(withToken && error.reponse.status === 401)
  await retryRequest();
return dispatch(apiError(label, error));
如果不能,请返回重试请求中的承诺,然后重试

if(withToken && error.response.status === 401)
  return retryRequest().then(_=> dispatch(apiError(label, error)))
return dispatch(apiError(label, error))
您也可以使用axios拦截器,这是我在最近的项目中使用的拦截器

api.interceptors.response.use(
功能(响应){
response.data=parseResponseData(response.data);
返回响应;
},
异步函数(错误){
如果(!error.response)
Ant.message.error('Não foi possivel se conctar com o servidor');
否则如果(
error.response.status==500&&
window.location.pathname!='/erro/500'
) {
if((error.config.method作为字符串).toLowerCase()='get')
导航('/erro/500');
其他的
Ant.message.error(
“请描述一下,我的意思是你不需要侍者。”,
);
}else if(error.response.status==401){
让request=error.config;
const auth=localStorage.getItem('auth');
让refreshToken=auth&&JSON.parse(auth)['refreshToken'];
var authService=new authService();
返回等待授权服务
.刷新(刷新令牌)
.然后(异步(响应)=>{
存储调度(登录(响应数据));
设axiosInstance=axios.create();
截距(轴向);
返回等待axiosInstance.request(请求);
})
.catch((e)=>{
如果(
window.location.pathname!='/login'&&
(!e.response | e.response.status==401)
)
导航('/login');
});
}
返回error.response;
},
);
到目前为止,它运作得相当不错