Categories
JavaScript Answers

How to send a https request to a rest service in Node.js and JavaScript?

Spread the love

Sometimes, we want to send a https request to a rest service in Node.js and JavaScript.

In this article, we’ll look at how to send a https request to a rest service in Node.js and JavaScript.

How to send a https request to a rest service in Node.js and JavaScript?

To send a https request to a rest service in Node.js and JavaScript, we use the https module.

For instance, we write

const https = require("https");

const options = {
  host: "www.example.com",
  port: 443,
  path: "/upload",
  method: "POST",
};

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

req.on("error", (e) => {
  console.log("problem with request: ", e.message);
});

to call https.request with the options object, which includes the URL, port, and the request method.

Then we get the response statusCode, headers, and the response body chunk in the request callback.

We listen for errors by calling req.on with 'error' and a error handler callback.

Conclusion

To send a https request to a rest service in Node.js and JavaScript, we use the https module.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published. Required fields are marked *