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

92,860

Solution 1

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)
})

Solution 2

i tried this and it seems to be working.I needed basic auth so i have included auth,if you don't need it you can discard it.

var value = {email:"",name:""};

 var options = {
        url: 'http://localhost:8080/doc/',
        auth: {
            user: username,
            password: password
        },
        method :"POST",
        json : value,

    };

    request(options, function (err, res, body) {
        if (err) {
            console.dir(err)
            return
        }
        console.dir('headers', res.headers)
        console.dir('status code', res.statusCode)
        console.dir(body)
    });

Solution 3

Just convert to a string and send.

post_req.write(JSON.stringify(post_data));
Share:
92,860
Prats
Author by

Prats

Working as a software engineer in one of the leading CMMI Level 5 company and doing all craps like you guys do :)

Updated on August 30, 2020

Comments

  • Prats
    Prats over 3 years

    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();
    
  • Ric
    Ric almost 8 years
    I'd like to verify something with you here. Is 'body: postData' correct or should postData be stringified, as in 'body: JSON.stringify(postData); ? thx.
  • Web User
    Web User almost 8 years
    @Noah how does this change if I want to use request.post(...)? Most requests the client application (an Electron app) will be sending contains JSON-based bodies, with the only exception being multipart bodies. I was having trouble with coming up with the right way of using this library and bodyParser settings in the Express (server side) application. I use app.use(bodyParser.json()) and app.use(bodyParser.urlencoded({ extended: true })); and requests failed to parse until I changed extended to false. Not sure how this is relevant to JSON requests, which is the cause of my confusion.
  • Sean
    Sean about 6 years
    @Ric Normally you'd be right, but adding json: true lets request know that it should stringify the payload before sending.