Skip to content
Advertisement

Send http request multiple times in node.js

I’m trying to send the same http request multiple times. I just put the request in a loop, but when I run the code it shows the response 1 time.

const req = https.request(options, res => {
  console.log(`statusCode: ${res.statusCode} ${res.statusMessage}`)

  res.on('data', d => {
    process.stdout.write(d)
  })
})

for(i=0; i<3; i++){ 
      req.write(data)
}

Advertisement

Answer

You should put the request inside the for loop:

for(i=0; i < 3; i++){ 
const req = https.request(options, res => {
  console.log(`statusCode: ${res.statusCode} ${res.statusMessage}`)

  res.on('data', d => {
    process.stdout.write(d)
  })
});
req.write(data);
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement