Axios: How to enable axios keepAlive?

Created on 22 Oct 2018  ·  2Comments  ·  Source: axios/axios

I want to use axios keepAlive.
but don't know how,Can you give me the answer?

Most helpful comment

keepAlive is something http specific. So you need to create a http or https agent. In order to achieve this, make sure to run the following command if not already done (just if you run it in the browser):

npm i http or npm i https

Then import it:
const axios = require('axios'); // or whatever module system you are using

Now you can create the http or https agent like this and pass the keepAlive flag as a property:

const httpAgent = new http.Agent({ keepAlive: true });
const httpsAgent = new https.Agent({ keepAlive: true });

Finally you need to pass the httpAgent as a property to your request or to your axios instance:

// on the instance
const instance = axios.create({
  httpAgent,  // httpAgent: httpAgent -> for non es6 syntax
  httpsAgent,
});

// on the request
axios.get('/user?ID=12345', { httpAgent }) // httpAgent: httpAgent -> for non es6 syntax
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })

All 2 comments

keepAlive is something http specific. So you need to create a http or https agent. In order to achieve this, make sure to run the following command if not already done (just if you run it in the browser):

npm i http or npm i https

Then import it:
const axios = require('axios'); // or whatever module system you are using

Now you can create the http or https agent like this and pass the keepAlive flag as a property:

const httpAgent = new http.Agent({ keepAlive: true });
const httpsAgent = new https.Agent({ keepAlive: true });

Finally you need to pass the httpAgent as a property to your request or to your axios instance:

// on the instance
const instance = axios.create({
  httpAgent,  // httpAgent: httpAgent -> for non es6 syntax
  httpsAgent,
});

// on the request
axios.get('/user?ID=12345', { httpAgent }) // httpAgent: httpAgent -> for non es6 syntax
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })

Here I found possible solution using agentkeepalive package

Was this page helpful?
0 / 5 - 0 ratings

Related issues

shaosh picture shaosh  ·  3Comments

altruisticsoftware picture altruisticsoftware  ·  3Comments

achingbrain picture achingbrain  ·  3Comments

jdpagley picture jdpagley  ·  3Comments

ghprod picture ghprod  ·  3Comments