JavaScript Answers

How to send a https request to a rest service in Node?

Spread the love

To send a https request to a rest service in Node, we use the https.request method.

For instance, we write

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) => {

req.on("error", (error) => {


to call https.request with the options object to make a request to

The object has the headers, the request method, the port and the path.

We get the response from res in the callback.

We get the status code with res.statusCode.

We get the response headers with res.headers.

And we get the response body from the data event callback’s d parameter.

We get errors from the error parameter from the error event handler.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.