Steps to Send a Https Request to a Rest Service in Node Js

Steps to Send a Https Request to a Rest Service in Node Js

What are the steps to send a https request in node js to a rest service? I have an api exposed like (Original link not working...)

How to pass the request and what are the options I need to give for this API like host, port, path and method?

1

5 Answers

just use the core https module with the https.request function. Example for a POST request (GET would be similar):

var https = require('https');

var options = {
  host: '
  port: 443,
  path: '/upload',
  method: 'POST'
};

var req = https.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();
4

The easiest way is to use the request module.

request(' function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body);
  }
});
7

Note if you are using https.request do not directly use the body from res.on('data',... This will fail if you have a large data coming in chunks. So you need to concatenate all the data and then process the response in res.on('end'. Example -

  var options = {
    hostname: "",
    port: 443,
    path: "/upload",
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': Buffer.byteLength(post_data)
    }
  };

  //change to http for local testing
  var req = https.request(options, function (res) {
    res.setEncoding('utf8');

    var body = '';

    res.on('data', function (chunk) {
      body = body + chunk;
    });

    res.on('end',function(){
      console.log("Body :" + body);
      if (res.statusCode != 200) {
        callback("Api call failed with response code " + res.statusCode);
      } else {
        callback(null);
      }
    });

  });

  req.on('error', function (e) {
    console.log("Error : " + e.message);
    callback(e);
  });

  // write data to request body
  req.write(post_data);
  req.end();
2

Using the request module solved the issue.

// Include the request library for Node.js   
var request = require('request');
//  Basic Authentication credentials   
var username = "vinod"; 
var password = "12345";
var authenticationHeader = "Basic " + new Buffer(username + ":" + password).toString("base64");
request(   
{
url : "",
headers : { "Authorization" : authenticationHeader }  
},
 function (error, response, body) {
 console.log(body); }  );         

Since there isn't any example with a ´GET´ method here is one. The catch is that the path in the options Object should be set to '/' in order to send the request correctly

const https = require('https')
const options = {
  hostname: '
  port: 443,
  path: '/',
  method: 'GET',
  headers: {
    'Accept': 'plain/html',
    'Accept-Encoding': '*',
  }
}

const req = https.request(options, res => {
  console.log(`statusCode: ${res.statusCode}`);
  console.log('headers:', res.headers);

  res.on('data', d => {
    process.stdout.write(d)
  })
})

req.on('error', error => {
  console.error(`Error on Get Request --> ${error}`)
})

req.end()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.