Introduction
Creating a web server is one of the first practical steps in learning Node.js backend development. Node.js provides the built-in http module, which lets you create a server without installing additional packages. In this chapter, you will practice starting a server, handling browser requests, sending HTML and JSON responses, creating routes, handling errors, and building a simple multi-page web server step by step. Node.js Creating Web Server practice questions with solutions help to understand the concepts.
Question 1: How do you create a basic web server in Node.js?
Problem
Create a Node.js web server that displays Welcome to my web server! when someone visits it.
Solution
const http = require("http");
const server = http.createServer((req, res) => {
res.end("Welcome to my web server!");
});
server.listen(3000, () => {
console.log("Server started on port 3000");
});
Output
Run:
node app.js
Terminal:
Server started on port 3000
Now open:
http://localhost:3000
Browser:
Welcome to my web server!
Step-by-Step Explanation
- Import the
httpmodule. - Create a server using
http.createServer(). reqcontains information about the browser request.resis used to send data back to the browser.res.end()sends the response.server.listen(3000)starts the server.- Open port
3000using your browser.
Question 2: How do you create a web server that returns HTML?
Problem
Create a server that displays a heading and paragraph as HTML.
Solution
const http = require("http");
const server = http.createServer((req, res) => {
res.writeHead(200, {
"Content-Type": "text/html"
});
res.end(`
<h1>My Node.js Web Server</h1>
<p>Welcome to my first website.</p>
`);
});
server.listen(3000, () => {
console.log("Server running at http://localhost:3000");
});
Output
The browser displays:
My Node.js Web Server
Welcome to my first website.
Step-by-Step Explanation
- Create the HTTP server.
- Use
res.writeHead()to set the response. 200means the request was successful.- Set
Content-Typetotext/html. - Send HTML using
res.end(). - Start the server on port
3000.
Important Point
The header:
"Content-Type": "text/html"
tells the browser to interpret the response as HTML.
Question 3: How do you create a web server with different routes?
Problem
Create three pages:
//about/contact
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>Home Page</h1>
<p>Welcome to our website.</p>
`);
} else if (req.url === "/about") {
res.statusCode = 200;
res.end(`
<h1>About Page</h1>
<p>This is our about page.</p>
`);
} else if (req.url === "/contact") {
res.statusCode = 200;
res.end(`
<h1>Contact Page</h1>
<p>Contact us for more information.</p>
`);
} else {
res.statusCode = 404;
res.end(`
<h1>404</h1>
<p>Page not found.</p>
`);
}
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Output
Visit:
http://localhost:3000/
You get:
Home Page
Welcome to our website.
Visit:
http://localhost:3000/about
You get:
About Page
This is our about page.
Visit:
http://localhost:3000/contact
You get:
Contact Page
Contact us for more information.
Step-by-Step Explanation
- Check
req.url. - If it is
/, show the home page. - If it is
/about, show the about page. - If it is
/contact, show the contact page. - For any unknown URL, return status
404. - Start the server.
This is the basic idea behind routing.
Question 4: How do you create a server that returns JSON data?
Problem
Create a web server that returns student information in JSON format.
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("JSON server started.");
});
Output
Open:
http://localhost:3000
The response will be:
{
"name": "Riya",
"age": 18,
"course": "Node.js"
}
Step-by-Step Explanation
- Create a JavaScript object.
- Set the response status to
200. - Set the content type to
application/json. - Convert the object into JSON using
JSON.stringify(). - Send the JSON using
res.end(). - Start the server.
This is the basic idea behind creating a simple API response.
Question 5: How do you display the HTTP request method on a web server?
Problem
Create a server that displays the HTTP method used by the client.
Solution
const http = require("http");
const server = http.createServer((req, res) => {
console.log("Request Method:", req.method);
res.end(
`Request method is ${req.method}`
);
});
server.listen(3000, () => {
console.log("Server started.");
});
Output
When you visit the website in a browser:
Terminal:
Request Method: GET
Browser:
Request method is GET
Step-by-Step Explanation
- Create the web server.
req.methodcontains the HTTP method.- A normal browser page request commonly uses
GET. - Display the method in the terminal.
- Send it back to the browser.
Common HTTP methods include:
GET
POST
PUT
PATCH
DELETE
Question 6: How do you serve a simple HTML page from a web server?
Problem
Create a server that returns a complete HTML document containing a title, heading, paragraph, and list.
Solution
const http = require("http");
const server = http.createServer((req, res) => {
res.writeHead(200, {
"Content-Type": "text/html"
});
const html = `
<!DOCTYPE html>
<html>
<head>
<title>Node.js Website</title>
</head>
<body>
<h1>Learn Node.js</h1>
<p>Welcome to Node.js web development.</p>
<h2>Popular Topics</h2>
<ul>
<li>JavaScript</li>
<li>Node.js</li>
<li>HTTP</li>
</ul>
</body>
</html>
`;
res.end(html);
});
server.listen(3000, () => {
console.log("Website running at http://localhost:3000");
});
Output
The browser displays:
Learn Node.js
Welcome to Node.js web development.
Popular Topics
• JavaScript
• Node.js
• HTTP
Step-by-Step Explanation
- Create an HTTP server.
- Set the content type to HTML.
- Store the HTML document inside a template literal.
- Send the HTML using
res.end(). - Start the server.
- Open it in your browser.
Why use backticks?
JavaScript template literals allow you to write multiple lines of HTML easily:
const html = `
<h1>Hello</h1>
<p>Welcome</p>
`;
Question 7: How do you handle a 404 page in a web server?
Problem
Create a server that shows a custom 404 page when the requested route does not exist.
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>Home Page</h1>
<p>Welcome!</p>
`);
} else {
res.statusCode = 404;
res.end(`
<h1>404 - Page Not Found</h1>
<p>Sorry, the page you requested does not exist.</p>
<a href="/">Go Home</a>
`);
}
});
server.listen(3000, () => {
console.log("Server started.");
});
Output
For:
http://localhost:3000/
you get:
Home Page
Welcome!
For:
http://localhost:3000/hello
you get:
404 - Page Not Found
Sorry, the page you requested does not exist.
Go Home
Step-by-Step Explanation
- Check the requested URL.
- If the URL is
/, return the home page. - Otherwise, set
res.statusCodeto404. - Send the custom error page.
- Provide a link back to the home page.
A 404 response tells the browser that the requested resource could not be found.
Question 8: How do you create a web server that reads query parameters?
Problem
Create a server that accepts a user’s name from the URL:
http://localhost:3000/?name=Riya
and displays:
Hello 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.setHeader(
"Content-Type",
"text/html"
);
if (name) {
res.end(`<h1>Hello ${name}!</h1>`);
} else {
res.end(`
<h1>Hello Guest!</h1>
<p>No name was provided.</p>
`);
}
});
server.listen(3000, () => {
console.log("Server started.");
});
Output
Open:
http://localhost:3000/?name=Riya
Browser:
Hello Riya!
If you open:
http://localhost:3000/
Browser:
Hello Guest!
No name was provided.
Step-by-Step Explanation
- Import the HTTP module.
- Import the
URLclass. - Create a complete URL from the incoming request.
- Use
searchParams.get("name"). - Store the name.
- Check whether a name was provided.
- Display the appropriate response.
Question 9: How do you create a web server with multiple routes and navigation links?
Problem
Create a small website containing:
- Home
- About
- Courses
- Contact
Each page should contain navigation links to the other pages.
Solution
const http = require("http");
const server = http.createServer((req, res) => {
res.setHeader(
"Content-Type",
"text/html"
);
const navigation = `
<nav>
<a href="/">Home</a> |
<a href="/about">About</a> |
<a href="/courses">Courses</a> |
<a href="/contact">Contact</a>
</nav>
<hr>
`;
if (req.url === "/") {
res.statusCode = 200;
res.end(`
${navigation}
<h1>Home Page</h1>
<p>Welcome to our Node.js website.</p>
`);
} else if (req.url === "/about") {
res.statusCode = 200;
res.end(`
${navigation}
<h1>About Us</h1>
<p>Learn more about our website.</p>
`);
} else if (req.url === "/courses") {
res.statusCode = 200;
res.end(`
${navigation}
<h1>Courses</h1>
<ul>
<li>Node.js</li>
<li>JavaScript</li>
<li>Python</li>
</ul>
`);
} else if (req.url === "/contact") {
res.statusCode = 200;
res.end(`
${navigation}
<h1>Contact Us</h1>
<p>Email: hello@example.com</p>
`);
} else {
res.statusCode = 404;
res.end(`
${navigation}
<h1>404 - Page Not Found</h1>
`);
}
});
server.listen(3000, () => {
console.log(
"Website running at http://localhost:3000"
);
});
Output
The home page contains:
Home | About | Courses | Contact
Home Page
Welcome to our Node.js website.
Clicking About opens:
/about
Clicking Courses opens:
/courses
Clicking Contact opens:
/contact
Step-by-Step Explanation
- Create the HTTP server.
- Set the response content type.
- Create a reusable navigation string.
- Check the requested URL.
- Return the appropriate page.
- Include navigation links on every page.
- Return a
404page for unknown URLs. - Start the server.
This example introduces the idea of reusable content while building routes manually.
Question 10: How do you build a complete beginner-friendly Node.js web server?
Problem
Build a small web server with:
- Home page
- About page
- Courses page
- JSON API
- 404 page
- Request logging
- Status codes
- HTML responses
Solution
const http = require("http");
const server = http.createServer((req, res) => {
console.log(
`${req.method} ${req.url}`
);
if (req.url === "/") {
res.writeHead(200, {
"Content-Type": "text/html"
});
res.end(`
<h1>Node.js Learning Website</h1>
<p>
Welcome to our website.
</p>
<a href="/about">About</a>
<br>
<a href="/courses">Courses</a>
<br>
<a href="/api/student">
Student API
</a>
`);
} else if (req.url === "/about") {
res.writeHead(200, {
"Content-Type": "text/html"
});
res.end(`
<h1>About</h1>
<p>
This website is created
using Node.js.
</p>
`);
} else if (req.url === "/courses") {
res.writeHead(200, {
"Content-Type": "text/html"
});
res.end(`
<h1>Courses</h1>
<ul>
<li>JavaScript</li>
<li>Node.js</li>
<li>Python</li>
</ul>
`);
} else if (req.url === "/api/student") {
const student = {
name: "Riya",
age: 18,
course: "Node.js"
};
res.writeHead(200, {
"Content-Type": "application/json"
});
res.end(
JSON.stringify(student)
);
} else {
res.writeHead(404, {
"Content-Type": "text/html"
});
res.end(`
<h1>404 - Page Not Found</h1>
<p>
The page you requested
does not exist.
</p>
<a href="/">
Go to Home
</a>
`);
}
});
server.listen(3000, () => {
console.log(
"Server running at http://localhost:3000"
);
});
Output
Start the server:
node app.js
Terminal:
Server running at http://localhost:3000
When you open the home page:
http://localhost:3000/
you get:
Node.js Learning Website
Welcome to our website.
About
Courses
Student API
Open:
http://localhost:3000/about
You get:
About
This website is created using Node.js.
Open:
http://localhost:3000/courses
You get:
Courses
• JavaScript
• Node.js
• Python
Open:
http://localhost:3000/api/student
You get JSON:
{
"name": "Riya",
"age": 18,
"course": "Node.js"
}
Open an unknown URL:
http://localhost:3000/test
You get:
404 - Page Not Found
The page you requested does not exist.
Go to Home
Step-by-Step Explanation
- Import the
httpmodule. - Create the web server.
- Log every incoming request using
req.methodandreq.url. - Create the home route.
- Create the about route.
- Create the courses route.
- Create a JSON API route.
- Set
Content-Typeaccording to the response. - Use
200for successful routes. - Use
404when the route does not exist. - Send responses using
res.end(). - Start the server on port
3000.
This example combines the main concepts you have learned so far about creating a Node.js web server.
Key Takeaways
- Node.js can create web servers using the built-in
httpmodule. http.createServer()creates the server.server.listen()starts the server on a specific port.reqcontains information about the incoming request.resis used to send information back to the client.req.urlhelps you create basic routes.req.methodtells you which HTTP method was used.res.end()finishes the response.res.writeHead()can set the status code and response headers.res.setHeader()can set individual response headers.- HTML responses normally use
Content-Type: text/html. - JSON responses normally use
Content-Type: application/json. - A
404status should be returned when a requested route does not exist. - Query parameters can be handled using the
URLandsearchParamsAPIs. - A Node.js web server can serve both HTML pages and API responses.
- Building a server with the HTTP module helps you understand the fundamentals behind Node.js backend frameworks.
FAQs
1. What is a web server in Node.js?
A web server is a program that listens for HTTP requests from clients such as web browsers and sends responses back to them.
Node.js can create a basic web server using its built-in http module.
const http = require("http");
const server = http.createServer((req, res) => {
res.end("Hello World");
});
2. How do I start a Node.js web server?
Use server.listen():
server.listen(3000, () => {
console.log("Server started.");
});
Then open:
http://localhost:3000
in your browser.
3. What does localhost:3000 mean?
localhost refers to your own computer.
3000 is the port number where your Node.js server is listening.
So:
http://localhost:3000
means that the browser should connect to port 3000 on your local computer.
4. What is the role of req and res when creating a web server?
req represents the incoming request.
You can use it to access:
req.url
req.method
req.headers
res represents the response that your server sends back.
You can use:
res.statusCode
res.setHeader()
res.writeHead()
res.end()
5. How do I create routes without Express?
You can check req.url manually:
if (req.url === "/about") {
res.end("About Page");
}
This works for learning and small applications. Larger applications usually use a web framework to make routing and request handling easier.
6. How do I send an HTML page from a Node.js server?
Set the content type to HTML and send the HTML using res.end():
res.writeHead(200, {
"Content-Type": "text/html"
});
res.end("<h1>Hello Node.js</h1>");
The browser will interpret the response as HTML.
7. Can Node.js create both websites and APIs?
Yes. A Node.js server can return HTML pages as well as JSON responses.
For example, an HTML route can return:
<h1>Home Page</h1>
while an API route can return:
{
"name": "Riya"
}
The response Content-Type should match the type of data being returned.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
