How should I pass json data in the request payload of http post request

Prats picture Prats · Apr 24, 2013 · Viewed 87.7k times · Source

I wanted to know, how to pass the json request in the payload, for eg: {'name' : 'test', 'value' : 'test'}:

var post_data = {};

var post_options = {
  host: this._host,
  path: path,
  method: 'POST',
  headers: {
    Cookie: "session=" + session,
    'Content-Type': 'application/json',
    'Content-Length': post_data.length,
  }
};

// Set up the request
var post_req = http.request(post_options, function (res) {
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('========Response========: ' + chunk);
  });
});

// post the data
post_req.write(post_data);
post_req.end();

Answer

Noah picture Noah · Apr 24, 2013

Use the request module

npm install -S request

var request = require('request')

var postData = {
  name: 'test',
  value: 'test'
}

var url = 'https://www.example.com'
var options = {
  method: 'post',
  body: postData,
  json: true,
  url: url
}
request(options, function (err, res, body) {
  if (err) {
    console.error('error posting json: ', err)
    throw err
  }
  var headers = res.headers
  var statusCode = res.statusCode
  console.log('headers: ', headers)
  console.log('statusCode: ', statusCode)
  console.log('body: ', body)
})