简体   繁体   中英

Override retry-axios default config

Here is the code being used to retry failed attempts at a token verification endpoint:

const axios = require('axios')
const rax = require('retry-axios')

try {
    const axiosInstance = axios.create();
    const myRaxConfig =  {
    instance: axiosInstance,
    retry: 4,
    statusCodesToRetry: [[100, 199], [401, 429, 429], [500, 501, 502, 504, 599]],
    httpMethodsToRetry: ['GET', 'HEAD', 'OPTIONS', 'DELETE', 'PUT', 'POST'],
    retryDelay: 100,
    noResponseRetries: 4,
    onRetryAttempt: (err) => {
        const cfg = rax.getConfig(err)
        console.log(`Retry attempt #${cfg.currentRetryAttempt}`);
    }
  }

  axiosInstance.defaults.raxConfig = myRaxConfig
  const interceptorId = rax.attach(axiosInstance);
  //const interceptorId = rax.attach()
  console.log("DOING THIS ONE +++++++++~~~~~~~~~~~~~~~~~~~~~~~")
  const tokenResult = await axiosInstance.post(`${process.env.URL}/api/token/verify`,
    {
      token
    },
  )
}
catch (err) {
   logger.error('encounter error in verify: ', err)
   //logger.error('encounter error in verify: ')

   return false
}

However, the error logs show that the default config is being used - and since this is a POST request, no retries were attempted:

Error output:

 ...
 "headers":{"Accept":"application/json, text/plain, */*","Content-Type":"application/json;charset=utf-8","User-Agent":"axios/0.19.0","Content-Length":252},"transformRequest":[null],"transformResponse":[null],"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1,
  "raxConfig":{"currentRetryAttempt":0,"retry":3,"retryDelay":100,"httpMethodsToRetry":["GET","HEAD","PUT","OPTIONS","DELETE"],"noResponseRetries":2,"statusCodesToRetry":[[100,199],[429,429],[500,599]]}}}

The axios request is using the default retry-axios config.

How can the default raxConfig be overwritten?

I went crazy to understand why my simply code like yours wasn't working.

Well, I think there is a bug in the library. This code which you can find in the npm library usage doesn't work properly:

const myAxiosInstance = axios.create();
myAxiosInstance.defaults.raxConfig = {
  instance: myAxiosInstance
};
const interceptorId = rax.attach(myAxiosInstance);
const res = await myAxiosInstance.get('https://test.local');

You have to add raxConfig object to your api call to make things work. Something like this:

const raxConfig = myAxiosInstance.defaults.raxConfig;
const res = await myAxiosInstance.get('https://test.local', { raxConfig } );

Don't forget to add "instance" property in it otherwise it doesn't work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM