OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Axios interceptor to retry sending FormData

  • Thread starter Thread starter 0xkvn
  • Start date Start date
0

0xkvn

Guest
I'm trying to create a "retry" functionality for a request containing a FormData as data. The retry happen when the JWT token is expired, my second request (the retry one) doesn't contain any data.

The idea:

Code:
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;
  });

The request:

Code:
  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
        }
      }
    );

If my token expired, the request will fail, the interceptor will then refresh my tokens, and retry the exact same request with just the new header Authorization. Yet, on the server side, the received payload is always null.

<p>I'm trying to create a "retry" functionality for a request containing a <code>FormData</code> as data.
The retry happen when the JWT token is expired, my second request (the retry one) doesn't contain any data.</p>
<p>The idea:</p>
<pre><code>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;
});
</code></pre>
<p>The request:</p>
<pre><code> 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
}
}
);
</code></pre>
<p>If my token expired, the request will fail, the interceptor will then refresh my tokens, and retry the exact same request with just the new header <code>Authorization</code>. Yet, on the server side, the received payload is always null.</p>
 

Latest posts

Online statistics

Members online
0
Guests online
3
Total visitors
3
Ads by Eonads
Top