What is the https.get() method in Node?

Node has in-built modules including http, https, and http2 that provide methods to implement and work with different HTTP protocols.

In this shot, we use the https module to get the data from a third-party API. The API we are going to use is https://catfact.ninja/fact.

Code

In this example, we try to get the data from a public API and print it on the console.

In the example below, you can copy and paste the API to check the response in your web browser.

const https = require('https');
https.get('https://catfact.ninja/fact', (resp)=>{
let data = '';
// A chunk of data has been received.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
console.log(data);
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});

The response from the API can have some events that happen during the response life cycle.

In this example we are using resp.on('data'...) which is fired when you get the data. resp.on('end'...) is fired at the end of the response.

  • In line 1, import the https module and create a variable.

  • In line 3, we use the https.get() method.

  • In line 5, create a variable that will store the incoming data.

  • In line 8, resp.on('data',callback()) listens for the data event which is fired when we get data.

  • In line 13, resp.on('end',callback()) listens for the end event which is fired when the response is ended.

  • In line 14, we print our incoming data on the console.

  • In line 17, https.get().on('error',callback()) listen for the error event, which is fired when the GET request comes across any error.

Output

We have successfully completed the 'get' request to get data from the others server. we have used a puplic API https://catfact.ninja/fact to test our get request.

You can run and check the console, it prints an object which is a string. You can use JSON.parse() to convert it to an object. It has fact and length properties, which was the data we were requesting.

Free Resources