So, you’ve been learning Node.js and now you’re ready to build something cool—a web server!
"But wait… isn’t that complicated?" you ask.
Nope! Thanks to Node.js’ built-in http
module, you can create an HTTP server in just a few lines of code. In this guide, we’ll break it all down in a fun and easy way—so grab a coffee (or tea, we don’t judge), and let’s get started!
What Is the http
Module in Node.js?
Before we start coding, let’s talk about what the http
module actually does.
The http
module is a built-in module in Node.js that allows you to create and handle HTTP servers and clients. In simpler terms, it’s the tool that lets you build websites and APIs directly from Node.js—without needing any external libraries!
With the http
module, you can:
- Create an HTTP server that listens for incoming requests.
- Send responses (like HTML, JSON, or plain text) back to the client.
- Handle different request types (GET, POST, etc.).
Now, let’s stop talking and start coding!
Step 1: Creating a Simple HTTP Server
Let’s create our first super simple HTTP server in Node.js.
1️ Open your terminal and create a new project folder:
mkdir my-first-server
cd my-first-server
2️ Create a new JavaScript file:
touch server.js
Or, if you’re using Windows:
echo. > server.js
3️ Open server.js
and write this code:
const http = require('http'); // Import the http module
// Create an HTTP server
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, world! Welcome to my Node.js server! ');
});
// Define the port number
const PORT = 3000;
// Start the server
server.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});
4️ Save the file and start your server:
node server.js
Boom! Your first Node.js server is now running!
Now, open your browser and go to http://localhost:3000. You should see:
Hello, world! Welcome to my Node.js server!
How Does This Work?
Let’s break down what just happened:
http.createServer()
: This creates a server that listens for HTTP requests.req
(request): Represents the incoming request from the client (browser, API, etc.).res
(response): Represents the response that we send back to the client.res.writeHead(200, { 'Content-Type': 'text/plain' })
: Sends a status code (200
means "OK") and sets the response type as plain text.res.end('Hello, world!')
: Sends the actual response message and closes the connection.server.listen(PORT, () => { console.log(...) })
: Starts the server and listens for requests on port 3000.
Step 2: Serving HTML Instead of Plain Text
Right now, our server only returns boring plain text. Let’s make it fancier by sending an HTML response instead.
Modify your server.js
file like this:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(`
<html>
<head><title>My First Node.js Server</title></head>
<body style="font-family: Arial, sans-serif; text-align: center;">
<h1>Hello, world! </h1>
<p>Welcome to my first Node.js web server! </p>
</body>
</html>
`);
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});
Now restart the server:
node server.js
Go to http://localhost:3000 again, and boom! Now you see a proper webpage instead of just text.
Step 3: Handling Different Routes
Right now, our server just returns the same response no matter what. But what if we want different pages for different routes (like /about
, /contact
)?
Update your server.js
file like this:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
if (req.url === '/') {
res.end('<h1>Home Page </h1><p>Welcome to my Node.js server!</p>');
} else if (req.url === '/about') {
res.end('<h1>About Us </h1><p>This is a simple server built with Node.js!</p>');
} else if (req.url === '/contact') {
res.end('<h1>Contact Us </h1><p>Email us at hello@example.com</p>');
} else {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('<h1>404 Not Found </h1><p>Oops! This page doesn’t exist.</p>');
}
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});
Now try visiting:
- http://localhost:3000/ → Shows "Home Page"
- http://localhost:3000/about → Shows "About Us"
- http://localhost:3000/contact → Shows "Contact Us"
- http://localhost:3000/random → Shows a 404 error
Step 4: Adding JSON Response (For API Development)
If you’re building an API, you’ll need to send JSON data instead of HTML. Let’s tweak our server to return JSON for the /api
route.
Modify the server.js
file:
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/api') {
res.writeHead(200, { 'Content-Type': 'application/json' });
const data = {
message: 'Hello from Node.js API!',
status: 'success'
};
res.end(JSON.stringify(data));
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});
Now visit http://localhost:3000/api, and you’ll see:
{
"message": "Hello from Node.js API!",
"status": "success"
}
Congratulations! You’ve just built a basic API in Node.js.
0 Comments