Creating a Simple HTTP Server
Introduction
In this lesson, we will learn how to create a simple HTTP server using Node.js. The HTTP server will listen for incoming requests and respond with specific content. This foundational knowledge is essential for building web applications and APIs. By the end of this lesson, you'll have a working server that can handle basic HTTP requests.
Setting Up Your Project
Before we start coding, let's set up a new Node.js project.
-
Create a New Directory: Open your terminal and create a new directory for your project:
mkdir simple-http-server cd simple-http-server
-
Initialize a New Node.js Project: Run the following command to create a
package.json
file:npm init -y
Creating the HTTP Server
Now, let's create a simple HTTP server using Node.js.
-
Create a New JavaScript File: Create a file named
server.js
in your project directory:touch server.js
-
Write the Server Code: Open
server.js
in your favorite code editor and add the following code:const http = require('http'); const hostname = '127.0.0.1'; // Localhost const port = 3000; // Port number const server = http.createServer((req, res) => { res.statusCode = 200; // HTTP status code res.setHeader('Content-Type', 'text/plain'); // Response header res.end('Hello, World!\n'); // Response body }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });
Understanding the Code
Let's break down the code to understand how it works:
-
Importing the HTTP Module: The first line imports the built-in
http
module, which provides the functionality to create an HTTP server. -
Defining Hostname and Port: The
hostname
variable is set to127.0.0.1
, which refers to the localhost. Theport
variable is set to3000
, which is the port number your server will listen on. -
Creating the Server: The
http.createServer()
method creates an instance of an HTTP server. It takes a callback function as an argument, which is called whenever an HTTP request is made. This function receives two parameters:req
: Represents the incoming request.res
: Represents the response that will be sent to the client.
-
Sending a Response: Inside the callback function:
res.statusCode
is set to200
, indicating a successful response.res.setHeader()
sets the content type of the response to plain text.res.end()
sends the response back to the client.
-
Listening for Incoming Requests: The
server.listen()
method binds the server to the specified hostname and port. It also takes a callback function that runs when the server starts listening, logging a message to the console.
Running the Server
To run your HTTP server, go back to your terminal and execute the following command:
node server.js
You should see the message indicating that the server is running:
Server running at http://127.0.0.1:3000/
Testing the Server
Now that your server is running, you can test it.
-
Open Your Web Browser: Navigate to
http://127.0.0.1:3000/
. -
Check the Response: You should see the message "Hello, World!" displayed in your browser. This confirms that your HTTP server is working correctly.
Handling Different Routes
You can extend your server to handle different routes by checking the req.url
property. Here's an example:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Welcome to the Home Page!\n');
} else if (req.url === '/about') {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('This is the About Page!\n');
} else {
res.statusCode = 404;
res.setHeader('Content-Type', 'text/plain');
res.end('404 Not Found\n');
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Explanation:
- The server checks the URL of incoming requests and responds accordingly.
- It sends a different message for the home page and about page, while returning a 404 error for undefined routes.
Conclusion
Congratulations! You have successfully created a simple HTTP server using Node.js. You learned how to set up a project, write server code, and handle basic routing. This foundational skill is crucial for building more complex web applications and APIs.