37

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();
Eliran Malka
  • 15,821
  • 6
  • 77
  • 100
Prats
  • 1,745
  • 4
  • 24
  • 28
  • Does this answer your question? http://stackoverflow.com/questions/4505809/how-to-post-to-a-request-using-node-js – exclsr Apr 24 '13 at 09:41

3 Answers3

100

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)
})
Noah
  • 33,851
  • 5
  • 37
  • 32
  • 5
    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. – Ric Jun 07 '16 at 23:09
  • @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. – Web User Jul 04 '16 at 01:56
  • 2
    @Ric Normally you'd be right, but adding `json: true` lets request know that it should stringify the payload before sending. – Sean Feb 06 '18 at 01:00
3

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

Just convert to a string and send.

post_req.write(JSON.stringify(post_data));
jemiloii
  • 24,594
  • 7
  • 54
  • 83