Node.js Routing Practice Questions with Solutions

Introduction

Routing determines what a Node.js server should do when a user visits a particular URL. For example, / can display the home page, /about can display an about page, and /courses can display courses. In this chapter, you will practice creating routes using Node.js and the built-in http module. You will learn basic routes, dynamic routes, query parameters, HTTP methods, 404 handling, and simple API routing step by step. Node.js Routing practice questions with solutions help to build concepts.

Question 1: How do you create a basic route in Node.js?

Problem

Create a Node.js server with a home route / that displays a welcome message.

Solution

const http = require("http");

const server = http.createServer((req, res) => {

    if (req.url === "/") {
        res.writeHead(200, {
            "Content-Type": "text/html"
        });

        res.end("<h1>Welcome to Node.js</h1>");
    }
});

server.listen(3000, () => {
    console.log("Server running at http://localhost:3000");
});

Output

Open:

http://localhost:3000/

Browser output:

Welcome to Node.js

Step-by-Step Explanation

  1. Import the http module.
  2. Create the server.
  3. Check req.url.
  4. If the URL is /, return the home page.
  5. Set the content type to HTML.
  6. Send the response using res.end().
  7. Start the server on port 3000.

Question 2: How do you create multiple routes in Node.js?

Problem

Create routes for:

  • /
  • /about
  • /contact

Solution

const http = require("http");

const server = http.createServer((req, res) => {

    res.setHeader("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.statusCode = 404;
        res.end("<h1>404 - Page Not Found</h1>");
    }
});

server.listen(3000, () => {
    console.log("Server started.");
});

Output

/:

Home Page

/about:

About Page

/contact:

Contact Page

Unknown route:

404 - Page Not Found

Step-by-Step Explanation

  1. Check the requested URL using req.url.
  2. Use if...else if to compare routes.
  3. Send a different response for each route.
  4. Set status 404 if no route matches.
  5. Start the server.

This is the simplest way to understand routing before using a framework.


Question 3: How do you create a 404 route?

Problem

Create a server that displays a custom 404 page whenever the user visits an unknown URL.

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>");

    } else if (req.url === "/about") {

        res.statusCode = 200;

        res.end("<h1>About Page</h1>");

    } else {

        res.statusCode = 404;

        res.end(`
            <h1>404 - Page Not Found</h1>
            <p>The requested page does not exist.</p>
            <a href="/">Go to Home</a>
        `);
    }
});

server.listen(3000, () => {
    console.log("Server running.");
});

Output

Visit:

http://localhost:3000/test

You will see:

404 - Page Not Found

The requested page does not exist.

Go to Home

Step-by-Step Explanation

  1. Check known routes.
  2. If no route matches, execute the final else.
  3. Set the status code to 404.
  4. Send a helpful error message.
  5. Add a link back to the home page.

Question 4: How do you create routes based on HTTP methods?

Problem

Create a route that responds differently to GET and POST requests.

Solution

const http = require("http");

const server = http.createServer((req, res) => {

    if (req.url === "/users") {

        if (req.method === "GET") {

            res.writeHead(200, {
                "Content-Type": "text/plain"
            });

            res.end("Getting users");

        } else if (req.method === "POST") {

            res.writeHead(201, {
                "Content-Type": "text/plain"
            });

            res.end("User created");

        } else {

            res.writeHead(405, {
                "Content-Type": "text/plain"
            });

            res.end("Method Not Allowed");
        }

    } else {

        res.writeHead(404, {
            "Content-Type": "text/plain"
        });

        res.end("Route Not Found");
    }
});

server.listen(3000, () => {
    console.log("Server running.");
});

Output

A GET request to:

/users

returns:

Getting users

A POST request to:

/users

returns:

User created

Step-by-Step Explanation

  1. First check the route.
  2. Check req.method.
  3. Handle GET.
  4. Handle POST.
  5. Return 405 for unsupported methods.
  6. Return 404 if the route itself does not exist.

Question 5: How do you create a route with query parameters?

Problem

Create a search route that accepts a product name:

http://localhost:3000/search?product=laptop

Solution

const http = require("http");
const { URL } = require("url");

const server = http.createServer((req, res) => {

    const currentUrl = new URL(
        req.url,
        `http://${req.headers.host}`
    );

    if (currentUrl.pathname === "/search") {

        const product =
            currentUrl.searchParams.get("product");

        res.writeHead(200, {
            "Content-Type": "text/html"
        });

        if (product) {
            res.end(`
                <h1>Search Result</h1>
                <p>You searched for: ${product}</p>
            `);
        } else {
            res.end(`
                <h1>Search</h1>
                <p>Please provide a product.</p>
            `);
        }

    } else {

        res.writeHead(404, {
            "Content-Type": "text/html"
        });

        res.end("<h1>Route Not Found</h1>");
    }
});

server.listen(3000, () => {
    console.log("Server started.");
});

Output

Open:

http://localhost:3000/search?product=laptop

Browser:

Search Result

You searched for: laptop

Step-by-Step Explanation

  1. Create a URL object.
  2. currentUrl.pathname gives the route.
  3. Check whether the route is /search.
  4. Use searchParams.get("product").
  5. Read the product name.
  6. Display it in the response.

Question 6: How do you create a dynamic route using the URL?

Problem

Create a route where the user can visit:

/user/Riya

and get:

Hello Riya

Solution

const http = require("http");

const server = http.createServer((req, res) => {

    const parts = req.url.split("/");

    if (parts[1] === "user" && parts[2]) {

        const username = parts[2];

        res.writeHead(200, {
            "Content-Type": "text/html"
        });

        res.end(`
            <h1>Hello ${username}</h1>
        `);

    } else {

        res.writeHead(404, {
            "Content-Type": "text/html"
        });

        res.end("<h1>404 - Route Not Found</h1>");
    }
});

server.listen(3000, () => {
    console.log("Server running.");
});

Output

Open:

http://localhost:3000/user/Riya

You get:

Hello Riya

Open:

http://localhost:3000/user/Aman

You get:

Hello Aman

Step-by-Step Explanation

For this URL:

/user/Riya

split("/") creates:

[
    "",
    "user",
    "Riya"
]

Therefore:

parts[1]

is:

user

and:

parts[2]

is:

Riya

This allows us to create a simple dynamic route.


Question 7: How do you create API routes in Node.js?

Problem

Create two API routes:

  • /api/users
  • /api/courses

Both routes should return JSON.

Solution

const http = require("http");

const server = http.createServer((req, res) => {

    res.setHeader(
        "Content-Type",
        "application/json"
    );

    if (req.url === "/api/users") {

        const users = [
            {
                id: 1,
                name: "Riya"
            },
            {
                id: 2,
                name: "Aman"
            }
        ];

        res.writeHead(200);

        res.end(JSON.stringify(users));

    } else if (req.url === "/api/courses") {

        const courses = [
            "JavaScript",
            "Node.js",
            "Python"
        ];

        res.writeHead(200);

        res.end(JSON.stringify(courses));

    } else {

        res.writeHead(404);

        res.end(
            JSON.stringify({
                error: "API route not found"
            })
        );
    }
});

server.listen(3000, () => {
    console.log("API server running.");
});

Output

Open:

http://localhost:3000/api/users

Response:

[
    {
        "id": 1,
        "name": "Riya"
    },
    {
        "id": 2,
        "name": "Aman"
    }
]

Open:

http://localhost:3000/api/courses

Response:

[
    "JavaScript",
    "Node.js",
    "Python"
]

Step-by-Step Explanation

  1. Set the response content type to JSON.
  2. Check whether the URL is /api/users.
  3. Create the users array.
  4. Convert it to JSON.
  5. Check /api/courses.
  6. Return the courses array.
  7. Return 404 for unknown API routes.

Question 8: How do you create reusable routing logic?

Problem

Create a simple routing function instead of putting all routing logic directly inside the server callback.

Solution

const http = require("http");

function handleRoute(req, res) {

    res.setHeader(
        "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.statusCode = 404;

        res.end("<h1>404 - Not Found</h1>");
    }
}

const server = http.createServer(handleRoute);

server.listen(3000, () => {
    console.log("Server started.");
});

Output

/:

Home Page

/about:

About Page

/contact:

Contact Page

Unknown route:

404 - Not Found

Step-by-Step Explanation

  1. Create a separate handleRoute() function.
  2. Pass req and res to the function.
  3. Put routing logic inside the function.
  4. Pass the function directly to http.createServer().
  5. Start the server.

Question 9: How do you create a route with multiple URL parameters?

Problem

Create a route such as:

/course/Node.js/18

where:

  • Node.js is the course name.
  • 18 is the student’s age.

Solution

const http = require("http");

const server = http.createServer((req, res) => {

    const parts = req.url.split("/");

    if (
        parts[1] === "course" &&
        parts[2] &&
        parts[3]
    ) {

        const course = parts[2];
        const age = parts[3];

        res.writeHead(200, {
            "Content-Type": "text/html"
        });

        res.end(`
            <h1>Course Details</h1>
            <p>Course: ${course}</p>
            <p>Student Age: ${age}</p>
        `);

    } else {

        res.writeHead(404, {
            "Content-Type": "text/html"
        });

        res.end(
            "<h1>Course Route Not Found</h1>"
        );
    }
});

server.listen(3000, () => {
    console.log("Server started.");
});

Output

Open:

http://localhost:3000/course/Node.js/18

Browser:

Course Details

Course: Node.js
Student Age: 18

Step-by-Step Explanation

The URL:

/course/Node.js/18

is divided into parts:

course
Node.js
18

The program stores:

const course = parts[2];
const age = parts[3];

The values are then displayed in the response.


Question 10: How do you build a complete Node.js routing system?

Problem

Create a small Node.js application with:

  • Home route
  • About route
  • Courses route
  • User dynamic route
  • Search route
  • API route
  • 404 handling

Solution

const http = require("http");
const { URL } = require("url");

function handleRoute(req, res) {

    const currentUrl = new URL(
        req.url,
        `http://${req.headers.host}`
    );

    const pathname = currentUrl.pathname;

    console.log(`${req.method} ${req.url}`);

    if (req.method !== "GET") {

        res.writeHead(405, {
            "Content-Type": "text/plain"
        });

        res.end("Method Not Allowed");

        return;
    }

    if (pathname === "/") {

        res.writeHead(200, {
            "Content-Type": "text/html"
        });

        res.end(`
            <h1>Home Page</h1>
            <p>Welcome to our Node.js website.</p>
        `);

    } else if (pathname === "/about") {

        res.writeHead(200, {
            "Content-Type": "text/html"
        });

        res.end(`
            <h1>About Page</h1>
            <p>Learn Node.js routing.</p>
        `);

    } else if (pathname === "/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 (pathname.startsWith("/user/")) {

        const username =
            pathname.split("/")[2];

        res.writeHead(200, {
            "Content-Type": "text/html"
        });

        res.end(`
            <h1>User Profile</h1>
            <p>Username: ${username}</p>
        `);

    } else if (pathname === "/search") {

        const keyword =
            currentUrl.searchParams.get("q");

        res.writeHead(200, {
            "Content-Type": "text/html"
        });

        if (keyword) {

            res.end(`
                <h1>Search</h1>
                <p>
                    You searched for:
                    ${keyword}
                </p>
            `);

        } else {

            res.end(`
                <h1>Search</h1>
                <p>Please enter a search term.</p>
            `);
        }

    } else if (pathname === "/api/courses") {

        const courses = [
            "JavaScript",
            "Node.js",
            "Python"
        ];

        res.writeHead(200, {
            "Content-Type": "application/json"
        });

        res.end(
            JSON.stringify(courses)
        );

    } else {

        res.writeHead(404, {
            "Content-Type": "text/html"
        });

        res.end(`
            <h1>404 - Page Not Found</h1>
            <p>The requested route does not exist.</p>
            <a href="/">Go Home</a>
        `);
    }
}

const server = http.createServer(handleRoute);

server.listen(3000, () => {
    console.log(
        "Server running at http://localhost:3000"
    );
});

Output

Home Route

Visit:

http://localhost:3000/

Output:

Home Page

Welcome to our Node.js website.

About Route

Visit:

http://localhost:3000/about

Output:

About Page

Learn Node.js routing.

Courses Route

Visit:

http://localhost:3000/courses

Output:

Courses

• JavaScript
• Node.js
• Python

Dynamic User Route

Visit:

http://localhost:3000/user/Riya

Output:

User Profile

Username: Riya

Search Route

Visit:

http://localhost:3000/search?q=node

Output:

Search

You searched for: node

API Route

Visit:

http://localhost:3000/api/courses

Output:

[
    "JavaScript",
    "Node.js",
    "Python"
]

Unknown Route

Visit:

http://localhost:3000/hello

Output:

404 - Page Not Found

The requested route does not exist.

Go Home

Step-by-Step Explanation

  1. Import the http module.
  2. Import the URL class.
  3. Create a separate handleRoute() function.
  4. Convert the request URL into a URL object.
  5. Get the pathname.
  6. Check the HTTP method.
  7. Create the home route.
  8. Create the about route.
  9. Create the courses route.
  10. Create a dynamic user route.
  11. Read the search query using searchParams.
  12. Create a JSON API route.
  13. Return 404 for unknown routes.
  14. Create the HTTP server using handleRoute.
  15. Start the server on port 3000.

This example combines the major routing concepts covered in this chapter.

Key Takeaways

  • Routing decides how a server responds to different URLs.
  • Node.js can handle basic routing using the built-in http module.
  • req.url can be used to identify the requested route.
  • req.method can be used to create method-specific routes.
  • if...else statements can create simple routes.
  • A 404 response should be returned for unknown routes.
  • 405 Method Not Allowed can be used when a route does not support the requested HTTP method.
  • Query parameters can be read using URL and searchParams.
  • Dynamic routes can be created by processing URL segments.
  • API routes can return JSON instead of HTML.
  • Separating routing logic into a function makes code easier to maintain.
  • The same route can behave differently depending on the HTTP method.
  • Node.js built-in routing is useful for learning how web frameworks work internally.
  • Frameworks such as Express provide more convenient routing features for larger applications.
  • Understanding routing is an important step toward building Node.js APIs and web applications.

FAQs

1. What is routing in Node.js?

Routing means deciding what response the server should send for a particular URL and HTTP method.

For example:

/

can show the home page, while:

/about

can show the about page.

2. How do I create a route in Node.js?

With the built-in http module, you can check req.url:

if (req.url === "/about") {
    res.end("About Page");
}

This is the basic idea behind manual routing.

3. What is a dynamic route?

A dynamic route contains a value that can change.

For example:

/user/Riya
/user/Aman
/user/John

The username is different in each URL.

You can read the value from the URL and use it in your response.

4. How do I handle a 404 route in Node.js?

Use a final condition for URLs that do not match your known routes:

res.statusCode = 404;
res.end("Page Not Found");

This tells the client that the requested route does not exist.

5. Can Node.js routing handle query parameters?

Yes. You can use the URL class and searchParams.

For example:

/search?q=node

The value of q can be retrieved with:

currentUrl.searchParams.get("q");

6. Can I create API routes using Node.js?

Yes. For example:

/api/courses
/api/users
/api/products

These routes can return JSON data instead of HTML.

res.end(JSON.stringify(data));

7. Should I use the Node.js HTTP module or Express for routing?

The built-in HTTP module is excellent for learning how routing works internally and for small applications.

For larger applications, frameworks such as Express generally make routing, middleware, request handling, and application organization easier.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top