Skip to main content
Node.js Basics
CHAPTER 09 Beginner

Node.js HTTP Module

Updated: May 13, 2026
20 min read

# Node.js HTTP Module

Welcome to Chapter 9! Up until now, we have been running scripts locally in our terminal. While that's useful for building CLI tools, the true power of Node.js is building Web Servers.

A web server is a program that listens for network requests (from browsers, mobile apps, etc.) and responds with data (HTML pages, JSON, images). In this chapter, we will build a real web server from scratch using Node's built-in http module.

---

1. Introduction

When you open Google Chrome and type http://www.google.com, your browser acts as the Client. It sends an HTTP Request across the internet. Google's computers act as the Server, receiving that request and sending back an HTTP Response containing the HTML for the Google homepage.

Node.js allows us to create the Server. The built-in http module provides all the tools necessary to listen to network ports, parse incoming requests, and format outgoing responses.

---

2. Learning Objectives

By the end of this chapter, you will be able to:

  • Require the built-in http module.
  • Create a basic web server using http.createServer().
  • Start the server and listen on a specific port.
  • Understand the request (req) and response (res) objects.
  • Send a basic text response to the browser.
  • Start and stop your server in the terminal.

---

3. Beginner-Friendly Explanations

What is a Port?

Think of an IP address (like 192.168.1.5) as the street address of an apartment building. The Port is the specific apartment number inside that building. A computer has thousands of ports. Browsers usually connect to Port 80 (HTTP) or 443 (HTTPS). Since we are developing locally, we will use an empty port like 3000 or 5000 for our Node.js server.

The Request (req) and Response (res) Cycle

Every time a user visits your server, Node.js triggers a callback function and hands you two powerful objects:
  1. 1. req (Request): Contains information about *what* the user wants (the URL they visited, their browser type, any data they submitted).
  1. 2. res (Response): Gives you the tools to send data *back* to the user.

---

4. Syntax Explanation

Here is the absolute bare minimum code to create a web server in Node.js.

```javascript id="ch9-syntax-1" // 1. Require the http module const http = require('http');

// 2. Create the server // This callback function runs EVERY time a request hits the server const server = http.createServer((req, res) => { // Write a response back to the client res.write('Hello from my first Node.js server!'); // End the response (crucial!) res.end(); });

// 3. Tell the server to listen on port 3000 server.listen(3000, () => { console.log('Server is running on http://localhost:3000'); });

123456789101112131415161718
**Output Explanation:**
When you run this file (`node server.js`), the terminal will **not** return to the prompt. It will hang. This means the server is actively listening! 
If you open Chrome and visit `http://localhost:3000`, your browser will display "Hello from my first Node.js server!".

---

## 5. Real-world Examples

**Why start with `http`?**
In modern development, we rarely use the raw `http` module because it takes too much code to build complex routing. Instead, we use a framework called **Express.js** (which we cover in Chapter 13). However, Express is built directly on top of this `http` module. Understanding how `req` and `res` work here is essential to truly mastering backend development.

---

## 6. Multiple Code Examples

### Example 1: Sending HTML
Instead of plain text, we can send HTML tags that the browser will render.

javascript id="ch9-code-1" const http = require('http');

const server = http.createServer((req, res) => { // Tell the browser we are sending HTML res.writeHead(200, { 'Content-Type': 'text/html' }); // Send HTML res.write('<h1>Welcome to my Backend</h1>'); res.write('<p>This is paragraph text sent from Node.js</p>'); res.end(); });

server.listen(5000, () => console.log('Listening on port 5000'));

123
### Example 2: Inspecting the Request (req) Object
Let's see what information the client is sending us.

javascript id="ch9-code-2" const http = require('http');

const server = http.createServer((req, res) => { console.log("A new request arrived!"); console.log("Requested URL:", req.url); console.log("HTTP Method:", req.method); // GET, POST, etc. res.end('Request received. Check your terminal.'); });

server.listen(4000, () => console.log('Listening on port 4000'));

12345678910111213141516171819202122232425262728293031323334353637383940414243
*If you visit `http://localhost:4000/about` in your browser, your terminal will log `Requested URL: /about`.*

---

## 7. Output Explanations

**What is `localhost`?**
`localhost` is a special domain name that loops back to your own computer. Its IP address is always `127.0.0.1`. Only *you* can access your localhost. Your friends cannot type `http://localhost:3000` on their computers to see your server. 

**Stopping the Server:**
Because the server listens indefinitely, you must manually stop it by clicking inside your terminal and pressing **`Ctrl + C`**.

---

## 8. Common Mistakes

1. **Forgetting `res.end()`:** If you write `res.write('hello')` but forget `res.end()`, the browser will spin and load forever, waiting for the server to say "I'm done sending data."
2. **Port already in use:** If you try to run `node server.js` and get an error `EADDRINUSE: address already in use :::3000`, it means you already have a server running on port 3000. You must stop the old one (`Ctrl + C`) before starting the new one.
3. **Not restarting the server after changes:** If you change your JavaScript code, the server will not automatically update. You must stop the server (`Ctrl+C`) and start it again (`node server.js`).

---

## 9. Best Practices

- **Use Status Codes:** Always set HTTP status codes. `200` means OK (success). `404` means Not Found. `500` means Server Error. You do this using `res.writeHead(200)`.
- **Set Content-Type Headers:** Browsers guess what type of data you are sending. It is best practice to explicitly tell them using headers: `{'Content-Type': 'text/html'}` or `{'Content-Type': 'application/json'}`.
- **Store Port in a Variable:** Don't hardcode `3000` in multiple places. Put it in a `const PORT = 3000;` at the top of your file.

---

## 10. Exercises

1. Create a server that listens on port `8080` and sends back an `<h1>` tag with your name.
2. Visit the server in your browser, and then visit `http://localhost:8080/fake-page`. Observe that the server still sends the exact same `<h1>` tag regardless of the URL.
3. Stop the server using `Ctrl + C`.

---

## 11. Mini Project: Simple HTTP server

**Objective:** Build an HTTP server that logs request details and responds with valid HTML.

**Code (`myServer.js`):**

javascript id="ch9-mini-project" // myServer.js const http = require('http'); const PORT = 3000;

const server = http.createServer((req, res) => { // 1. Log the request to the terminal console.log([${new Date().toLocaleTimeString()}] Request made to: ${req.url});

// 2. Set the response headers res.writeHead(200, { 'Content-Type': 'text/html' });

// 3. Construct an HTML string const htmlResponse = <html> <head> <title>My Node Server</title> <style> body { font-family: Arial; text-align: center; margin-top: 50px; } h1 { color: #026e00; } </style> </head> <body> <h1>Node.js Server is Active! 🚀</h1> <p>You requested the path: <strong>${req.url}</strong></p> </body> </html> ;

// 4. Send the response and close the connection res.end(htmlResponse); });

server.listen(PORT, () => { console.log(✅ Server is live at http://localhost:${PORT}); console.log(Press Ctrl + C to stop the server.); }); ``

Run it: node myServer.js -> Open Chrome to http://localhost:3000

---

12. Coding Challenges

Challenge 1: Modify the server to check req.url. If the user visits /secret, send back text that says "You found the secret area!". If they visit anything else, send "Welcome home."

Challenge 2: Write a server that responds with {'Content-Type': 'application/json'} and sends back a stringified JavaScript object JSON.stringify({ name: "Alice", age: 25 }).

---

13. MCQs with Answers

Q1: Which core module allows Node.js to create web servers? A) net B) web C) http D) server Answer: C

Q2: What happens if you forget to call res.end() in your request handler? A) Node.js will automatically close it. B) The application crashes. C) The client's browser will hang and load indefinitely. D) It sends an empty response. Answer: C

Q3: How do you gracefully stop a running Node.js server in the terminal? A) Type .exit B) Press Ctrl + C C) Press Esc D) Type stop Answer: B

Q4: In the callback (req, res), what does req stand for? A) Requirement B) Request C) Response D) Receive Answer: B

---

14. Interview Questions

  1. 1. What is the difference between req and res in the http module?
*Answer:* req (Request) is an object containing information about the incoming client request (URL, headers, HTTP method). res (Response) is an object used to send data, headers, and status codes back to the client.
  1. 2. What does the .listen() method do?
*Answer:* It binds the created server to a specific network port (like 3000) and starts a background loop, keeping the Node.js process alive and waiting for incoming connections.
  1. 3. What is HTTP status code 200 vs 404?
*Answer:* 200 indicates a successful request ("OK"). 404 indicates that the server could not find the requested resource ("Not Found").

---

15. FAQs

Q: Why do I see a request for /favicon.ico in my terminal? A: Modern browsers automatically request favicon.ico behind the scenes to try and load a little icon for the browser tab. Your server is logging this automated request!

Q: Do I have to restart the server every time I save a file? A: Yes, natively Node.js requires a restart. However, developers use an NPM package called nodemon to automatically restart the server upon saving. We will learn about this soon!

---

16. Summary

  • The http module is used to create web servers.
  • http.createServer(callback) triggers the callback on every incoming request.
  • The req object reads incoming data (like the URL).
  • The res object sends outgoing data (HTML, text) and must always be closed using res.end().
  • Servers listen on Ports (e.g., 3000), and are accessed locally via http://localhost:3000.

---

17. Next Chapter Recommendation

Right now, our server sends the exact same response no matter what URL the user visits. If they go to /about or /contact, they get the same page. In Chapter 10: Creating a Basic Web Server, we will learn Routing—how to send different pages based on the URL, and how to read HTML from physical files using the fs` module!

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·