Axios拦截器重试发送FormData

2022-09-03 00:00:00 axios javascript interceptor
我正在尝试为包含FormDataAS数据的请求创建";retry";功能。 重试发生在JWT令牌过期时,我的第二个请求(重试请求)不包含任何数据。

创意:

const axiosInstance = axios.create();

  /**
   * Before each request, we'll add a possible retry if the
   * request need a refreshed token
   */
  axiosInstance.interceptors.request.use((request) => {
    if (typeof _.get(request, ['retried']) === 'undefined') {
      request.retried = false;
    }

    return request;
  });

/**
   * After a request with an error, we'll check if the error is a token not refreshed.
   * If we didn't already tried to refresh, we'll just fallback to the errorHandler function
   */
  axiosInstance.interceptors.response.use(null, async (error) => {
    const statusCode = _.get(error, ['response', 'data', 'statusCode']);
    const message = _.get(error, ['response', 'data', 'message']);
    const { config: request = {} } = error;

    if (statusCode === 401 && !request.retried) {
      try {
        const newTokens = await refreshTokens();
        request.retried = true;
        _.set(request, ['headers', 'authorization'], newTokens.accessToken);
        return axiosInstance.request(request);
      } catch (e) {
        return error;
      }
    }
    return error;
  });

请求:

  const formData = new FormData();
  formData.append('name', name);
  formData.append('file', fs.createReadStream(file.path));

  axiosInstance.post(
      'http://localhost/upload',
      formData,
      {
        headers: {
          ...formData.getHeaders(),
          authorization: tokens.accessToken
        }
      }
    );

如果我的令牌过期,请求将失败,然后拦截器将刷新我的令牌,并仅使用新的标头Authorization重试完全相同的请求。但是,在服务器端,收到的有效负载始终为空。


解决方案

据我所知,FormData需要在重试时重新添加(我认为这是因为数据是以流的形式添加的,在请求过程中被消费了,所以新的重试不能消费已经消费的流)。

您可以查看request.data,了解我的意思。

相关文章