简体   繁体   中英

Node.js https.request() Error: socket hang up

I'm using plain node.js script to make a POST request and the link that I make request to takes around 1 to 1.2 mins to respond and in that time I get this error Error: socket hang up .

I get the socket hang up error around the same time as I would have gotten the response from the server which is around 1 to 1.2 mins

I've tried setting connection: "keep-alive" in headers and setting timeout to 200000ms in options but no luck. Any help?

BTW the request works fine if i use axios

Here's my script

const fs = require("fs")
const path = require("path")
const https = require("https")

const file = fs.createWriteStream(path.join(__dirname, "data.csv"))

const options = {
  hostname: "example.com",
  path: "/example",
  method: "POST",
  headers: {
    <<headers>>
  }
  <<some other options>>
}

const req = https.request(options, response => {
    response.on("data", function (chunk) {
      console.log("started...")
      chunk.pipe(file)
    })
    response.on("end", function () {
      file.on("finish", function () {
        file.close()
      })
    })
  })

req.on("error", e => {
  console.error(e)
})
req.end()

This is the full error:

Error: socket hang up
    at connResetException (internal/errors.js:612:14)
    at TLSSocket.socketOnEnd (_http_client.js:493:23)
    at TLSSocket.emit (events.js:326:22)
    at endReadableNT (_stream_readable.js:1308:12)
    at processTicksAndRejections (internal/process/task_queues.js:80:21) {
  code: 'ECONNRESET'
}

Found the mistake i was making

First instead of doing chunk.pipe(file) inside response.on('data') i directly did response.pipe(file) and it worked i don't know why exactly, i'm guessing it's because response is the stream and chunk is just the buffer, if anybody knows then please tell me.

Second i was setting the request body inside options, i had to set the request body parameter like this req.write(formData) where formData is a string that i want to send as request body.

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