Node.js https.post request

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

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 with a POST request, including data like:

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

      

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

+3


source to share


1 answer


In the options object, you include the request parameters as you did in the GET request, and you create another object containing the data you want to receive into your POST body. You underline this using the querystring function (which you must set with npm install querystring

) and then forwarding it using the write () and end () methods of https.request ().

It's important to note that you need two additional headers in the options object in order to make a successful post request. It:

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

      



so you will probably need to run the parameters object after querystring.stringify returns. Otherwise, you will not know the length of the gated body data.

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


postData = {   //the POST request 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();

      

+5


source







All Articles