HTTP POST request using Node.js

Danny Morris

2019/07/15

This simple snippet demonstrates how to use Node to make a POST request.

const https = require('http')

const data = JSON.stringify({
  doc_set_1: 'hello'
})

const options = {
  hostname: 'ec2-instance-dns.com',
  port: '8000',
  path: '/textsim',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length
  }
}

const req = https.request(options, (res) => {
  console.log(`statusCode: ${res.statusCode}`)
  
  res.on(
    'data', (d) => {
      process.stdout.write(d)
    }
  )
})

req.on('error', (error) => {
  console.error(error)
})

req.write(data)
req.end()