HTTP Module in Node.js

HTTP Module in Node.js

The Built-in HTTP Module

To start with, Node.js has some built-in modules. These modules work just like every other modules that can be installed via npm and then include using the import or require syntax, but as the name implies, built-in modules are already installed and hence, always available.

The Node.js HTTP Module

The HTTP is one of the many built-in modules and it allows Node.js to transfer data over the HYPER TEXT TRANSFER PROTOCOL (HTTP). It is used for creating networking applications, example, a web server that listens for http requests on a given port, hence you can create a Backend service for your client application.

The HTTP module has various classes like the http.Agent and each classes has a bunch of properties, methods and events.

How to use the HTTP Module

Firstly, create a file called app.js and include the HTTP Module by using the require() method:

const http = require('http')

Secondly, create an HTTP server by using the createServer() method of the http object. The HTTP server created listens to server ports and gives a response back to the client.

const server = http.createServer((req, res) => {
     if (req.url === '/') {
           res.write('<h1>Hello World</h1>')
}
     res.end()
})

The createServer() accepts a callback with two arguments: HTTP request req and response res. Inside the callback function, you send an HTML string to the browser if the url is / (the supposed Home page) and after that, you end the request.

Thirdly, you give the server a port by using the server.listen() method. You can use 3000

server.listen(3000)
console.log(`The HTTP server is running on port : 3000`)

You can then proceed to the terminal to run the application, example:

node app.js

Output:

The HTTP server is running on port : 3000

At this point, you can launch the web browser and go to the URL localhost:3000. You'll see the message:

Hello World

You can exit from the terminal by using CTRL + C

This simple example explains how to use the http module.

If you want to build a backend service for your website or an application, you need to handle various routes by having multiple if statements.

In the real world, you won't use the http module to build a backend service for your application because the code gets more complex by adding more routes and you do so linearly inside the callback function, hence, you use a framework called Express which gives your application a clean structure to handle various routes.

Internally, the Express framework is built on top of the Node.js HTTP module.

Want to read more on HTTP classes? click here