Node.js HTTP Module

Summary: in this tutorial, you will learn about the Node.js http module and how to use it to create a simple HTTP server.

Introduction to the Node.js HTTP module

The http module is a core module of Node designed to support many features of the HTTP protocol.

The following example shows how to use the http module:

First, create a new file called server.js and include the http module by using the require() function:

const http = require('http');Code language: JavaScript (javascript)

Second, create an HTTP server using the createServer() method of the http object.

const server = http.createServer((req, res) => {
    if (req.url === '/') {
        res.write('<h1>Hello, Node.js!</h1>');
    }
    res.end();
});Code language: JavaScript (javascript)

The createServer() accepts a callback that has two parameters: HTTP request (req) and response (res). Inside the callback, we send an HTML string to the browser if the URL is / and end the request.

Third, listen to the incoming HTTP request on the port 5000:

server.listen(5000);
console.log(`The HTTP Server is running on port 5000`);Code language: JavaScript (javascript)

Put it all together:

const http = require('http');

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

server.listen(5000);
console.log(`The HTTP Server is running on port 5000`);Code language: JavaScript (javascript)

The following starts the HTTP server:

node server.jsCode language: JavaScript (javascript)

Output:

The HTTP Server is running on port 5000Code language: JavaScript (javascript)

Now, you can launch the web browser and go to the URL http://localhost:5000/. You’ll see the following message:

Hello, Node.jsCode language: JavaScript (javascript)

This simple example illustrates how to use the http module. In practice, you will not use the http module directly. Instead, you will use a popular module called express to handle HTTP requests and responses.

Was this tutorial helpful ?