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');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();
});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`);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`);The following starts the HTTP server:
node server.jsOutput:
The HTTP Server is running on port 5000Now, you can launch the web browser and go to the URL http://localhost:5000/. You’ll see the following message:
Hello, Node.jsThis 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.
Thank you for your feedback!