HTTP Module

HTTP Module

The HTTP module is one of the most fundamental built-in modules in the backend ecosystem. It enables your application to transfer data over the Hyper Text Transfer Protocol (HTTP), which is the foundation of data communication on the World Wide Web.

With this module, you can easily create robust web servers that listen for requests and send back responses, allowing you to build APIs, render websites, and serve data to clients worldwide.


1. Importing the HTTP Module

Since HTTP is a core module, you do not need to install anything using NPM. You simply require it at the top of your file:

const http = require('http');

2. Creating a Basic Web Server

The most common use case for the HTTP module is creating a web server. We use the http.createServer() method, which accepts a callback function with two arguments: req (the incoming request) and res (the outgoing response).

Creating a Server

const http = require('http');

// Create a server object const server = http.createServer((req, res) => { // Set the response HTTP header with HTTP status and Content type res.writeHead(200, { 'Content-Type': 'text/plain' }); // Send the response body res.end('Hello, World! Welcome to the HTTP Module.'); });

// Use port 0 so Node picks a free port for this self-contained demo server.listen(0, () => { const { port } = server.address();

console.log('Server is running on http://127.0.0.1:' + port);

http.get('http://127.0.0.1:' + port, (response) => { let body = ''; response.on('data', (chunk) => { body += chunk; }); response.on('end', () => { console.log('Response from server:', body); server.close(); }); }); });

Understanding the Flow

  1. http.createServer(): Creates the server instance.
  2. req: Contains information about the user's request (like the URL they visited).
  3. res: The object used to send data back to the user.
  4. server.listen(...): Tells the server to start actively listening for requests on a port.

3. Making HTTP Requests

You can also use the HTTP module to act as a client and make requests to other servers using http.get() or http.request(). However, for modern applications, developers often prefer newer APIs like fetch or external libraries like axios for client-side requests.


Exercise

?

Which method is used to create a web server using the HTTP module?