Node.js Creating Web Server Practice Questions with Solutions

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

  1. Import the http module.
  2. Create a server using http.createServer().
  3. req contains information about the browser request.
  4. res is used to send data back to the browser.
  5. res.end() sends the response.
  6. server.listen(3000) starts the server.
  7. Open port 3000 using 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

  1. Create the HTTP server.
  2. Use res.writeHead() to set the response.
  3. 200 means the request was successful.
  4. Set Content-Type to text/html.
  5. Send HTML using res.end().
  6. 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

  1. Check req.url.
  2. If it is /, show the home page.
  3. If it is /about, show the about page.
  4. If it is /contact, show the contact page.
  5. For any unknown URL, return status 404.
  6. 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

  1. Create a JavaScript object.
  2. Set the response status to 200.
  3. Set the content type to application/json.
  4. Convert the object into JSON using JSON.stringify().
  5. Send the JSON using res.end().
  6. 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

  1. Create the web server.
  2. req.method contains the HTTP method.
  3. A normal browser page request commonly uses GET.
  4. Display the method in the terminal.
  5. 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

  1. Create an HTTP server.
  2. Set the content type to HTML.
  3. Store the HTML document inside a template literal.
  4. Send the HTML using res.end().
  5. Start the server.
  6. 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

  1. Check the requested URL.
  2. If the URL is /, return the home page.
  3. Otherwise, set res.statusCode to 404.
  4. Send the custom error page.
  5. 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

  1. Import the HTTP module.
  2. Import the URL class.
  3. Create a complete URL from the incoming request.
  4. Use searchParams.get("name").
  5. Store the name.
  6. Check whether a name was provided.
  7. 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

  1. Create the HTTP server.
  2. Set the response content type.
  3. Create a reusable navigation string.
  4. Check the requested URL.
  5. Return the appropriate page.
  6. Include navigation links on every page.
  7. Return a 404 page for unknown URLs.
  8. 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

  1. Import the http module.
  2. Create the web server.
  3. Log every incoming request using req.method and req.url.
  4. Create the home route.
  5. Create the about route.
  6. Create the courses route.
  7. Create a JSON API route.
  8. Set Content-Type according to the response.
  9. Use 200 for successful routes.
  10. Use 404 when the route does not exist.
  11. Send responses using res.end().
  12. 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 http module.
  • http.createServer() creates the server.
  • server.listen() starts the server on a specific port.
  • req contains information about the incoming request.
  • res is used to send information back to the client.
  • req.url helps you create basic routes.
  • req.method tells 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 404 status should be returned when a requested route does not exist.
  • Query parameters can be handled using the URL and searchParams APIs.
  • 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:

&lt;h1>Home Page&lt;/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.

Scroll to Top