Node.js HTTP Module Practice Questions with Solutions

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

  1. Import the built-in http module.
  2. Use http.createServer() to create a server.
  3. The callback receives two important objects:
    • req — contains information about the incoming request.
    • res — is used to send a response.
  4. res.end() sends the response and finishes it.
  5. server.listen(3000) starts the server on port 3000.
  6. Open localhost:3000 in 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

  1. Create an HTTP server.
  2. Use res.writeHead() to set the response status and headers.
  3. 200 means the request was successful.
  4. "Content-Type": "text/html" tells the browser that the response contains HTML.
  5. Use res.end() to send the HTML.
  6. 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

  1. The browser sends an HTTP request.
  2. Node.js stores request information inside req.
  3. req.url contains the requested URL path.
  4. console.log() displays it.
  5. 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

  1. Check req.url.
  2. Compare it with /.
  3. If it matches, send the Home page.
  4. Check /about.
  5. Check /contact.
  6. If none matches, send a 404 response.
  7. A 404 status 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

  1. req.method contains the HTTP request method.
  2. A normal browser page request commonly uses GET.
  3. Compare the method using ===.
  4. 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

  1. Check the requested URL.
  2. If the page exists, use status code 200.
  3. If the page does not exist, use status code 404.
  4. res.writeHead() sets the status code and response headers.
  5. res.end() sends the response.

Common Status Codes

Status CodeMeaning
200OK
201Created
301Moved Permanently
400Bad Request
401Unauthorized
403Forbidden
404Not Found
500Internal 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

  1. Import the http module.
  2. Import the URL class.
  3. Create a URL using the incoming request.
  4. Access searchParams.
  5. Use .get("name") to retrieve the name.
  6. 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

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

  1. Check whether the requested URL is /old.
  2. Use status code 302 for a temporary redirect.
  3. Set the Location header to /new.
  4. End the response.
  5. The browser follows the redirect.
  6. The /new route 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

  1. Import the http module.
  2. Create an HTTP server.
  3. Set the response Content-Type to HTML.
  4. Check req.url.
  5. Create a response for the home page.
  6. Create a response for the about page.
  7. Create a response for the courses page.
  8. Create a response for the contact page.
  9. Return a 404 response for unknown URLs.
  10. Start the server on port 3000.

This example combines several important HTTP concepts into one beginner-friendly application.

Key Takeaways

  • The Node.js http module is a built-in module for creating HTTP servers.
  • Use require("http") to import it in CommonJS.
  • http.createServer() creates an HTTP server.
  • req represents the incoming request.
  • res represents the outgoing response.
  • req.url provides the requested URL.
  • req.method provides the HTTP method.
  • res.end() sends the response and ends it.
  • res.writeHead() can set the status code and headers.
  • res.statusCode can be used to set the response status.
  • Content-Type tells the client what kind of data is being returned.
  • 200 usually represents a successful response.
  • 404 means the requested resource was not found.
  • 302 can be used for a temporary redirect.
  • JSON responses should normally use Content-Type: application/json.
  • Query parameters can be read using the URL and searchParams APIs.
  • 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.

Scroll to Top