Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js https.post request [duplicate]

I am using Node.js and I need to send a POST request containing specific data to an external server. I am doing the same thing with GET, but this is a lot easier since I don't have to include the additional data. So, my working GET request looks like:

var options = {
    hostname: 'internetofthings.ibmcloud.com',
    port: 443,
    path: '/api/devices',
    method: 'GET',
    auth: username + ':' + password
};
https.request(options, function(response) {
    ...
});

So I was wondering how to do the same thing with POST request, including data such as:

type: deviceType,
id: deviceId,
metadata: {
    address: {
        number: deviceNumber,
        street: deviceStreet
    }
}

Could anyone tell me how to include this data to the options above? Thanks in advance!

like image 455
Nhor Avatar asked Jul 24 '15 08:07

Nhor


1 Answers

In the options object you include the request options as you did in the GET request and you create one more object containing the data you want in your POST's body. You stringify that using the querystring function (which you need to install by npm install querystring) and then you forward it by using the write() and end() methods of https.request().

It is important to note that you need two extra headers in your options object in order to make a successful post request. These are :

'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postBody.length

so you probably need to init your options object after querystring.stringify has returned. Otherwise you won't know the length of the stringified body data.

var querystring = require('querystring')
var https = require('https')


postData = {   //the POST request's body data
   type: deviceType,
   id: deviceId,
   metadata: {
      address: {
         number: deviceNumber,
         street: deviceStreet
      }
   }            
};

postBody = querystring.stringify(postData);
//init your options object after you call querystring.stringify because you  need
// the return string for the 'content length' header

options = {
   //your options which have to include the two headers
   headers : {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Content-Length': postBody.length
   }
};


var postreq = https.request(options, function (res) {
        //Handle the response
});
postreq.write(postBody);
postreq.end();
like image 86
Dimitris P. Avatar answered Sep 24 '22 14:09

Dimitris P.