How do I use JSON in the body of an http PUT in node.js?

Nathan McKaskle picture Nathan McKaskle · Sep 1, 2015 · Viewed 9.5k times · Source

See my code below. I am trying to send { "status" : "accepted" } in the body of my request. The error I keep getting back from the API on their end is:

{"message":"Unable to parse JSON in request body.","code":"invalid_json"}

I can make this work in Swift but with that I'm using a dictionary object with the settings and serializing it. I don't know how to do that in Node.JS.

var https = require('https')

var options = {
    "host": "sandbox-api.uber.com",
    "path": "/v1/sandbox/requests/" + req.body.request_id,
    "method": "PUT",
    "headers": { 
    "Authorization" : "Bearer " + req.body.bearer_token,
    "Content-Type" : "application/json",
    },
    "body" : {
        "status" : "accepted"
    }
}

callback = function(response) {
    var str = ''
    response.on('data', function(chunk){
        str += chunk
    })

    response.on('end', function(){
        console.log(str)
    })
}

https.request(options, callback).end()

Answer

mscdex picture mscdex · Sep 1, 2015

You write it to the request object like:

var https = require('https')

var options = {
  "host": "sandbox-api.uber.com",
  "path": "/v1/sandbox/requests/" + req.body.request_id,
  "method": "PUT",
  "headers": { 
    "Authorization" : "Bearer " + req.body.bearer_token,
    "Content-Type" : "application/json",
  }
}

callback = function(response) {
  var str = ''
  response.on('data', function(chunk){
    str += chunk
  })

  response.on('end', function(){
    console.log(str)
  })
}

var body = JSON.stringify({
  status: 'accepted'
});
https.request(options, callback).end(body);