NodeJS axios: read ECONNRESET when calling same api multiple times

214 views Asked by At

I am trying to call an api 500 times, it returns correct response for around 300 times but throws the ECONNRESET in between the request. When I call the same api from my C# code, it works fine. In the C# code, it takes approx 20-25 seconds to complete all the requests. I have tried to change default timeout, add http and httpsAgent keepalive: true config but still the error is occuring.

axios.default.defaults.timeout = 20000;
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0;

const getToken = async (id, username, password) => {
    let data = JSON.stringify({
        "username": username,
        "password": password
    });
      
    let config = {
        method: 'post',
        maxBodyLength: Infinity,
        
        url: 'URL',
        headers: { 
          'Accept': 'application/json, text/plain, */*', 
          'Accept-Language': 'en-GB,en-US;q=0.9,en;q=0.8', 
          'Authorization': '[object Object]', 
          'Connection': 'keep-alive', 
          'Content-Type': 'application/json', 
          'Origin': 'URL', 
          'Referer': 'URL', 
          'Sec-Fetch-Dest': 'empty', 
          'Sec-Fetch-Mode': 'cors', 
          'Sec-Fetch-Site': 'same-site', 
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36', 
          'sec-ch-ua': '"Google Chrome";v="113", "Chromium";v="113", "Not-A.Brand";v="24"', 
          'sec-ch-ua-mobile': '?0', 
          'sec-ch-ua-platform': '"Windows"'
        },
        data : data
    };
    try {
        const response = await axios.request(config);
        agent_tokens[id] = response.data.access_token;
        console.log(`${id}: Token created`);
        return response.data.access_token;
    } catch (err) {
        console.log(`[Token creation ${id}]: Error occured` + err);
        console.log(err);
        agent_tokens[id] = null;
        return null;
    }


const createTokens = async() => {
    var tokensPromise = [];
    for (var i = 0; i < data.length; i++) {
        tokensPromise.push(getToken(data[i].id, data[i].username, data[i].password));
    }

    await Promise.all(tokensPromise).then(values => {
        console.log(`Promise completed`);
    })
    return;
}

In between the request it throws the ECONNRESET error

0

There are 0 answers