CLOSE

Node.js includes built-in modules – http and https, that let us create both servers and clients for the respective protocols.

HTTP Module

The http module is used to create web servers and handle HTTP requests and responses.

Server Example:

const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello, world!');
});

server.listen(3000, () => {
  console.log('HTTP Server is listening on port 3000');
});
  • Client Requests:
    • This module also allows us to make outgoing HTTP requests using methods like http.get() and http.request().

HTTPS Module

The https module is very similar to http, but it is designed for secure communication over TLS/SSL. It is used create secure servers or make secure requests.

Secure Server Example:

const https = require('https');
const fs = require('fs');

const options = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem')
};

const server = https.createServer(options, (req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Secure Hello, world!');
});

server.listen(3000, () => {
  console.log('HTTPS Server is listening on port 3000');
});
  • Client Requests:
    • You can also make secure client requests using https.get() or https.request() in a manner similar to the http module.