Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle socket hangup error in NodeJs using Axios

I am using Axios to call a post API from nodejs. Sometimes it is throwing socket hangup error. I have seen solutions for this issue like, catch this error and retry the request again. But since it is a post request for updating some details in DB, we cant hit it again.

  const httpsAgent = new https.Agent({
      rejectUnauthorized: false
    });

const response = await axios({
      url,
      method: Constants.POST,
      data,
      httpsAgent,
      proxy: false,
      headers: {
        "Content-Type": "application/json",
        Authorization: bearerToken
      }
    });

Error we are getting is : socket hang up

Do anyone have idea about how to resolve this issue?

We have created this nodejs code as a Lambda in aws and the API we are calling is in EC2 server.

like image 416
Pranav Malanthra Avatar asked Oct 14 '25 08:10

Pranav Malanthra


1 Answers

I checked that key option is keepAlive: true for "https.Agent"

Try to use

const client = axios.create({
    timeout: 60000,
    maxContentLength: 500 * 1000 * 1000,
    httpsAgent: new https.Agent({ keepAlive: true }),
}) 

instead of default axios.

like image 104
Daniel Avatar answered Oct 18 '25 03:10

Daniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!