Introduction
The Node.js http module allows you to create web servers and handle HTTP requests and responses without installing an external package. It is one of the most important Node.js modules for understanding backend development. In this chapter, you will practice creating servers, handling requests, sending responses, working with URLs and methods, setting status codes, and building a simple HTTP application step by step. Node.js HTTP Module practice questions with solutions help to understand the concepts.
Question 1: How do you create a basic HTTP server in Node.js?
Problem
Create a simple HTTP server that sends Hello, Node.js! to the browser.
Solution
const http = require("http");
const server = http.createServer((req, res) => {
res.end("Hello, Node.js!");
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Output
In the terminal:
Server running on port 3000
Open:
http://localhost:3000
You will see:
Hello, Node.js!
Step-by-Step Explanation
- Import the built-in
httpmodule. - Use
http.createServer()to create a server. - The callback receives two important objects:
req— contains information about the incoming request.res— is used to send a response.
res.end()sends the response and finishes it.server.listen(3000)starts the server on port3000.- Open
localhost:3000in your browser.
Question 2: How do you send an HTML response from an HTTP server?
Problem
Create a server that displays a simple HTML heading and paragraph in the browser.
Solution
const http = require("http");
const server = http.createServer((req, res) => {
res.writeHead(200, {
"Content-Type": "text/html"
});
res.end(`
<h1>Welcome to Node.js</h1>
<p>This is my first HTTP server.</p>
`);
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Output
The browser displays:
Welcome to Node.js
This is my first HTTP server.
Step-by-Step Explanation
- Create an HTTP server.
- Use
res.writeHead()to set the response status and headers. 200means the request was successful."Content-Type": "text/html"tells the browser that the response contains HTML.- Use
res.end()to send the HTML. - Start the server on port
3000.
Important Point
Without the correct Content-Type, the browser may not handle the response as expected.
Question 3: How do you check the URL requested by the user?
Problem
Create a server that displays the requested URL in the terminal.
Solution
const http = require("http");
const server = http.createServer((req, res) => {
console.log("Requested URL:", req.url);
res.end("Request received.");
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Example
Open:
http://localhost:3000/about
Terminal output:
Requested URL: /about
If you open:
http://localhost:3000/contact
the terminal will show:
Requested URL: /contact
Step-by-Step Explanation
- The browser sends an HTTP request.
- Node.js stores request information inside
req. req.urlcontains the requested URL path.console.log()displays it.res.end()sends a response to the browser.
Question 4: How do you create different pages using req.url?
Problem
Create a server with three routes:
//about/contact
Solution
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>");
} else if (req.url === "/about") {
res.end("<h1>About Page</h1>");
} else if (req.url === "/contact") {
res.end("<h1>Contact Page</h1>");
} else {
res.writeHead(404, {
"Content-Type": "text/html"
});
res.end("<h1>404 - Page Not Found</h1>");
}
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Output
Open:
http://localhost:3000/
You get:
Home Page
Open:
http://localhost:3000/about
You get:
About Page
Open:
http://localhost:3000/contact
You get:
Contact Page
For an unknown route:
http://localhost:3000/test
You get:
404 - Page Not Found
Step-by-Step Explanation
- Check
req.url. - Compare it with
/. - If it matches, send the Home page.
- Check
/about. - Check
/contact. - If none matches, send a
404response. - A
404status means the requested resource was not found.
Question 5: How do you check the HTTP request method?
Problem
Display whether the incoming request is a GET or another HTTP method.
Solution
const http = require("http");
const server = http.createServer((req, res) => {
console.log("Request Method:", req.method);
if (req.method === "GET") {
res.end("This is a GET request.");
} else {
res.end("This is another HTTP method.");
}
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Output
When you open the page in a browser:
Request Method: GET
Browser response:
This is a GET request.
Step-by-Step Explanation
req.methodcontains the HTTP request method.- A normal browser page request commonly uses
GET. - Compare the method using
===. - Send a different response based on the method.
Common HTTP methods include:
GET
POST
PUT
PATCH
DELETE
Question 6: How do you set an HTTP status code?
Problem
Create a server that returns a 404 status when a page does not exist.
Solution
const http = require("http");
const server = http.createServer((req, res) => {
if (req.url === "/") {
res.writeHead(200, {
"Content-Type": "text/html"
});
res.end("<h1>Home Page</h1>");
} else {
res.writeHead(404, {
"Content-Type": "text/html"
});
res.end("<h1>404 - Page Not Found</h1>");
}
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Output
For:
http://localhost:3000/
the response status is:
200 OK
For:
http://localhost:3000/test
the response status is:
404 Not Found
Step-by-Step Explanation
- Check the requested URL.
- If the page exists, use status code
200. - If the page does not exist, use status code
404. res.writeHead()sets the status code and response headers.res.end()sends the response.
Common Status Codes
| Status Code | Meaning |
|---|---|
| 200 | OK |
| 201 | Created |
| 301 | Moved Permanently |
| 400 | Bad Request |
| 401 | Unauthorized |
| 403 | Forbidden |
| 404 | Not Found |
| 500 | Internal Server Error |
Question 7: How do you read query parameters from a URL?
Problem
Create a server that reads a user’s name from this URL:
http://localhost:3000/?name=Riya
Solution
const http = require("http");
const { URL } = require("url");
const server = http.createServer((req, res) => {
const website = new URL(
req.url,
`http://${req.headers.host}`
);
const name = website.searchParams.get("name");
res.end(`Hello ${name}!`);
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Output
Open:
http://localhost:3000/?name=Riya
Browser output:
Hello Riya!
Step-by-Step Explanation
- Import the
httpmodule. - Import the
URLclass. - Create a URL using the incoming request.
- Access
searchParams. - Use
.get("name")to retrieve the name. - Send the name in the response.
You can also try:
http://localhost:3000/?name=Aman
Output:
Hello Aman!
Question 8: How do you serve JSON from an HTTP server?
Problem
Create an HTTP server that returns student information as JSON.
Solution
const http = require("http");
const server = http.createServer((req, res) => {
const student = {
name: "Riya",
age: 18,
course: "Node.js"
};
res.writeHead(200, {
"Content-Type": "application/json"
});
res.end(
JSON.stringify(student)
);
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Output
The browser or API client receives:
{
"name": "Riya",
"age": 18,
"course": "Node.js"
}
Step-by-Step Explanation
- Create a JavaScript object.
- Set the response status to
200. - Set
Content-Typetoapplication/json. - Convert the JavaScript object into JSON using
JSON.stringify(). - Send the JSON using
res.end().
Important Point
When sending JSON, use:
Content-Type: application/json
This tells the client that the response contains JSON data.
Question 9: How do you create a simple redirect using the HTTP module?
Problem
Create a server where visiting /old redirects the user to /new.
Solution
const http = require("http");
const server = http.createServer((req, res) => {
if (req.url === "/old") {
res.writeHead(302, {
Location: "/new"
});
res.end();
} else if (req.url === "/new") {
res.writeHead(200, {
"Content-Type": "text/html"
});
res.end("<h1>Welcome to the New Page</h1>");
} else {
res.writeHead(404, {
"Content-Type": "text/html"
});
res.end("<h1>Page Not Found</h1>");
}
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Output
Open:
http://localhost:3000/old
The browser will redirect to:
http://localhost:3000/new
and display:
Welcome to the New Page
Step-by-Step Explanation
- Check whether the requested URL is
/old. - Use status code
302for a temporary redirect. - Set the
Locationheader to/new. - End the response.
- The browser follows the redirect.
- The
/newroute sends the final page.
Question 10: How do you build a simple multi-route HTTP application?
Problem
Create a small Node.js website with these routes:
/→ Home/about→ About/courses→ Courses/contact→ Contact- Any other URL → 404
Solution
const http = require("http");
const server = http.createServer((req, res) => {
res.setHeader(
"Content-Type",
"text/html"
);
if (req.url === "/") {
res.statusCode = 200;
res.end(`
<h1>VSIT Home Page</h1>
<p>Welcome to our website.</p>
`);
} else if (req.url === "/about") {
res.statusCode = 200;
res.end(`
<h1>About Us</h1>
<p>Learn more about our institute.</p>
`);
} else if (req.url === "/courses") {
res.statusCode = 200;
res.end(`
<h1>Our Courses</h1>
<ul>
<li>Python</li>
<li>JavaScript</li>
<li>Node.js</li>
</ul>
`);
} else if (req.url === "/contact") {
res.statusCode = 200;
res.end(`
<h1>Contact Us</h1>
<p>Email: example@example.com</p>
`);
} else {
res.statusCode = 404;
res.end(`
<h1>404 - Page Not Found</h1>
<p>The requested page does not exist.</p>
`);
}
});
server.listen(3000, () => {
console.log(
"Server running at http://localhost:3000"
);
});
Output
Open:
http://localhost:3000/
You will see:
VSIT Home Page
Welcome to our website.
Open:
http://localhost:3000/about
You will see:
About Us
Learn more about our institute.
Open:
http://localhost:3000/courses
You will see:
Our Courses
Python
JavaScript
Node.js
Open:
http://localhost:3000/contact
You will see:
Contact Us
Email: example@example.com
For an unknown URL:
http://localhost:3000/test
You will see:
404 - Page Not Found
The requested page does not exist.
Step-by-Step Explanation
- Import the
httpmodule. - Create an HTTP server.
- Set the response
Content-Typeto HTML. - Check
req.url. - Create a response for the home page.
- Create a response for the about page.
- Create a response for the courses page.
- Create a response for the contact page.
- Return a
404response for unknown URLs. - Start the server on port
3000.
This example combines several important HTTP concepts into one beginner-friendly application.
Key Takeaways
- The Node.js
httpmodule is a built-in module for creating HTTP servers. - Use
require("http")to import it in CommonJS. http.createServer()creates an HTTP server.reqrepresents the incoming request.resrepresents the outgoing response.req.urlprovides the requested URL.req.methodprovides the HTTP method.res.end()sends the response and ends it.res.writeHead()can set the status code and headers.res.statusCodecan be used to set the response status.Content-Typetells the client what kind of data is being returned.200usually represents a successful response.404means the requested resource was not found.302can be used for a temporary redirect.- JSON responses should normally use
Content-Type: application/json. - Query parameters can be read using the
URLandsearchParamsAPIs. - The HTTP module is an important foundation for understanding Node.js backend development.
- Frameworks such as Express build on concepts that you first learn with Node.js HTTP handling.
FAQs
1. What is the HTTP module in Node.js?
The http module is a built-in Node.js module used to create HTTP servers and handle HTTP requests and responses.
const http = require("http");
It allows you to build basic web servers without installing an external package.
2. How do you create an HTTP server in Node.js?
Use http.createServer():
const http = require("http");
const server = http.createServer((req, res) => {
res.end("Hello Node.js!");
});
server.listen(3000);
The server listens for requests on port 3000.
3. What are req and res in Node.js HTTP?
req stands for request. It contains information about the request sent by the client.
For example:
req.url
req.method
req.headers
res stands for response. It is used to send data back to the client.
For example:
res.statusCode
res.setHeader()
res.end()
4. What does res.end() do?
res.end() finishes the HTTP response and can also send the final response data.
res.end("Hello World");
After the response is completed, the client receives the data.
5. What is the difference between req.url and req.method?
req.url tells you which URL the client requested:
/about
req.method tells you which HTTP method was used:
GET
For example:
console.log(req.url);
console.log(req.method);
6. How do I return JSON from a Node.js HTTP server?
Set the correct content type and convert the JavaScript object into JSON:
const data = {
name: "Riya",
age: 18
};
res.writeHead(200, {
"Content-Type": "application/json"
});
res.end(JSON.stringify(data));
7. Can I create a website using only the Node.js HTTP module?
Yes. You can create basic websites and APIs using the built-in HTTP module. You can handle routes, request methods, headers, status codes, query parameters, and responses manually.
However, larger applications commonly use frameworks such as Express because they provide convenient routing, middleware, request handling, and other features.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
