NodeJS JSON Post

Uses the https://httpbin.org /anything JSON echo service to demonstrate how to POST JSON encoded data to a URI.  

  • Have nodejs installed on your machine
  • Run the file or text interactively nodejs <file_with_following_contents>

Code

const https = require('https')

const data = JSON.stringify({
  message: 'mittens on kittens'
})

const options = {
  hostname: 'httpbin.org',
  port: 443,
  path: '/anything',
  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()

Expected Response

statusCode: 200
{
  "args": {}, 
  "data": "{\"message\":\"mittens on kittens\"}", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Content-Length": "32", 
    "Content-Type": "application/json", 
    "Host": "httpbin.org"
  }, 
  "json": {
    "message": "mittens on kittens"
  }, 
  "method": "POST", 
  "origin": "71.15.103.85, 71.15.103.85", 
  "url": "https://httpbin.org/anything"
}