Open In App

Node.js https.request() Function

Last Updated : 19 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Https request function in Node is used to make the http request over secure http or https. It provide more control to the request like setting headers, http methods, adding request data and handle the responses.

https.request(options, callback)

It is a part of https module and allows to send different requests like GET, POST,, PUT, DELETE etc. to interact with the web servers.

Feature of https module

  • It is easy to get started and easy to use.
  • It is widely used and popular module for making https calls.

Example: The example uses https.request funtion to make GET request to the API and console log the data.

JavaScript
// Filename: index.js

const https = require('https');

// Sample URL
const url = 'https://jsonplaceholder.typicode.com/todos/1';

const request = https.request(url, (response) => {
    let data = '';
    response.on('data', (chunk) => {
        data = data + chunk.toString();
    });

    response.on('end', () => {
        const body = JSON.parse(data);
        console.log(body);
    });
})

request.on('error', (error) => {
    console.log('An error', error);
});

request.end() 

Steps to run the program: Run index.js file using below command:

node index.js
Output of above command

So this is how you can use the https.request() function to make https request calls.

Summary

https.request is a part of https module and is used to make request using https i.e. secured http with the web servers. It allow to make GET, POST, PUT, DELETE requests along with headers, request datga and handle responses.



Next Article

Similar Reads