Node.js HTTP Module
# 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
httpmodule.
-
Create a basic web server using
http.createServer().
- Start the server and listen on a specific port.
-
Understand the
request(req) andresponse(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 (like192.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.
req(Request): Contains information about *what* the user wants (the URL they visited, their browser type, any data they submitted).
-
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'); });
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'));
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'));
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.
What is the difference between req
andresin the http module?
(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.
-
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.
-
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!