I want to use axios keepAlive.
but don't know how,Can you give me the answer?
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
Most helpful comment
keepAlive
is somethinghttp
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
ornpm 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:Finally you need to pass the httpAgent as a property to your request or to your axios instance: