Node.js HTTP Request and Response Practice Questions with Solutions

Introduction

HTTP requests and responses are the foundation of communication between a browser and a Node.js server. The request object contains information sent by the client, while the response object is used to send data back. In this chapter, you will practice reading URLs, HTTP methods, headers, query parameters, status codes, response headers, HTML responses, JSON responses, and handling different requests step by step. Node.js HTTP Request and Response practice questions with solutions help to understand the concepts.

Question 1: How do you read the URL from an HTTP request?

Problem

Create a Node.js server that displays the URL requested by the user.

Solution

const http = require("http");

const server = http.createServer((req, res) => {
    console.log("Requested URL:", req.url);

    res.end(`You requested: ${req.url}`);
});

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

Output

Open:

http://localhost:3000/about

Terminal:

Requested URL: /about

Browser:

You requested: /about

Step-by-Step Explanation

  1. Import the http module.
  2. Create the server.
  3. The req object represents the incoming request.
  4. req.url contains the requested URL.
  5. Display the URL in the terminal.
  6. Send the same URL back to the browser using res.end().

Question 2: How do you read the HTTP request method?

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("HTTP Method:", req.method);

    res.end(`Method used: ${req.method}`);
});

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

Output

When you open the website in a browser:

HTTP Method: GET

Browser:

Method used: GET

Step-by-Step Explanation

  1. req.method contains the HTTP request method.
  2. Browser page requests normally use GET.
  3. Store or use the method as needed.
  4. Send it back using the response object.

Common HTTP methods include:

GET
POST
PUT
PATCH
DELETE

Question 3: How do you read request headers?

Problem

Create a server that displays the browser’s User-Agent header.

Solution

const http = require("http");

const server = http.createServer((req, res) => {
    console.log(
        "User-Agent:",
        req.headers["user-agent"]
    );

    res.end("Request header received.");
});

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

Output

The terminal will display information similar to:

User-Agent: Mozilla/5.0 ...

The exact value depends on the browser being used.

Step-by-Step Explanation

  1. HTTP requests contain headers.
  2. Node.js makes request headers available through req.headers.
  3. "user-agent" identifies information about the client or browser.
  4. Use bracket notation to access the header.
  5. Send a response to the client.

You can display all headers using:

console.log(req.headers);

Question 4: How do you send a custom response header?

Problem

Create a server that sends a custom header called X-App-Name.

Solution

const http = require("http");

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

    res.setHeader(
        "X-App-Name",
        "Node Learning Server"
    );

    res.end("Custom header sent.");
});

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

Output

Browser response:

Custom header sent.

The response also contains:

X-App-Name: Node Learning Server

Step-by-Step Explanation

  1. Create the HTTP server.
  2. Use res.setHeader() to create a response header.
  3. The first argument is the header name.
  4. The second argument is the header value.
  5. Send the response using res.end().

The general syntax is:

res.setHeader("Header-Name", "Header-Value");

Question 5: How do you set the response status code?

Problem

Create a server that returns a 404 status when the requested page does not exist.

Solution

const http = require("http");

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

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

        res.statusCode = 200;

        res.end("Home Page");

    } else {

        res.statusCode = 404;

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

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

Output

Open:

http://localhost:3000/

Response:

Home Page

Status:

200 OK

Open:

http://localhost:3000/test

Response:

Page Not Found

Status:

404 Not Found

Step-by-Step Explanation

  1. Check the requested URL.
  2. If it is /, set the status to 200.
  3. Otherwise, set the status to 404.
  4. Send the appropriate response.

Question 6: How do you send an HTML response?

Problem

Create a server that sends a properly formatted HTML response.

Solution

const http = require("http");

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

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

    res.end(`
        <h1>Node.js HTTP Response</h1>
        <p>This response contains HTML.</p>
    `);
});

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

Output

The browser displays:

Node.js HTTP Response

This response contains HTML.

Step-by-Step Explanation

  1. Create the server.
  2. Set status code 200.
  3. Set Content-Type to text/html.
  4. Create HTML content.
  5. Send the content using res.end().

The response header tells the browser how to interpret the data.


Question 7: How do you send a JSON response?

Problem

Create a server that returns student information as JSON.

Solution

const http = require("http");

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

    const student = {
        name: "Aarav",
        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

The response will be:

{
    "name": "Aarav",
    "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 object into JSON using JSON.stringify().
  5. Send the JSON response.

Question 8: How do you read query parameters from an HTTP request?

Problem

Read the user’s name from:

http://localhost:3000/?name=Riya

and display a greeting.

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}`
    );

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

    res.setHeader(
        "Content-Type",
        "text/html"
    );

    if (name) {
        res.end(`<h1>Hello ${name}!</h1>`);
    } else {
        res.end("<h1>Hello Guest!</h1>");
    }
});

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

Output

Open:

http://localhost:3000/?name=Riya

Browser:

Hello Riya!

Open:

http://localhost:3000/

Browser:

Hello Guest!

Step-by-Step Explanation

  1. Import http.
  2. Import the URL class.
  3. Create a URL object from the request.
  4. Access searchParams.
  5. Use .get("name") to read the query parameter.
  6. Check whether a name was provided.
  7. Send the appropriate response.

Question 9: How do you handle GET and POST requests differently?

Problem

Create a server that returns different messages for GET and POST requests.

Solution

const http = require("http");

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

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

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

        res.end(`
            <h1>GET Request</h1>
            <p>You sent a GET request.</p>
        `);

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

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

        res.end(`
            <h1>POST Request</h1>
            <p>You sent a POST request.</p>
        `);

    } else {

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

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

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

Output

A normal browser request uses GET, so visiting:

http://localhost:3000

returns:

GET Request

You sent a GET request.

A POST request sent by a suitable HTTP client would return:

POST Request

You sent a POST request.

Step-by-Step Explanation

  1. Check req.method.
  2. If it is GET, send the GET response.
  3. If it is POST, send the POST response.
  4. For unsupported methods, return status 405.
  5. 405 means the HTTP method is not allowed for that resource.

Question 10: How do you handle a request and response in a complete Node.js example?

Problem

Create a small server that:

  • Logs the request method and URL.
  • Handles /.
  • Handles /about.
  • Returns JSON from /api/student.
  • Returns 404 for unknown routes.
  • Uses appropriate response headers and status codes.

Solution

const http = require("http");

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

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

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

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

        res.end("Method Not Allowed");

        return;
    }

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

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

        res.end(`
            <h1>Home Page</h1>
            <p>Welcome to our Node.js website.</p>
            <a href="/about">About</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 Page</h1>
            <p>
                This website uses Node.js.
            </p>
        `);

    } 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>
            <a href="/">Go to Home</a>
        `);
    }
});

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

Output

When you visit:

http://localhost:3000/

you get:

Home Page

Welcome to our Node.js website.

About
Student API

When you visit:

http://localhost:3000/about

you get:

About Page

This website uses Node.js.

When you visit:

http://localhost:3000/api/student

you get:

{
    "name": "Riya",
    "age": 18,
    "course": "Node.js"
}

For an unknown URL such as:

http://localhost:3000/test

you get:

404 - Page Not Found
Go to Home

The terminal also displays requests such as:

GET /
GET /about
GET /api/student
GET /test

Step-by-Step Explanation

  1. Create an HTTP server.
  2. Log the incoming request method and URL.
  3. Check whether the request uses GET.
  4. Return 405 if another method is used.
  5. Check the requested URL.
  6. Return HTML for /.
  7. Return HTML for /about.
  8. Return JSON for /api/student.
  9. Return 404 for an unknown route.
  10. Set the appropriate Content-Type.
  11. Set the appropriate HTTP status code.
  12. Finish every response with res.end().

This example brings together the main request and response concepts you need before moving toward more advanced Node.js backend development.

Key Takeaways

  • An HTTP request is sent from a client to a server.
  • An HTTP response is sent from the server back to the client.
  • Node.js provides request information through the req object.
  • Node.js provides response methods through the res object.
  • req.url gives you the requested URL.
  • req.method gives you the HTTP request method.
  • req.headers contains incoming request headers.
  • res.setHeader() creates or modifies a response header.
  • res.writeHead() can set status codes and headers together.
  • res.statusCode allows you to set the response status.
  • res.end() finishes the response.
  • Content-Type tells the client what kind of data the response contains.
  • HTML responses commonly use text/html.
  • JSON responses commonly use application/json.
  • Query parameters can be accessed using URL and searchParams.
  • 404 means the requested resource was not found.
  • 405 means the HTTP method is not allowed.
  • GET and POST requests can be handled differently.
  • Understanding request and response objects is essential for Node.js backend development.

FAQs

1. What is an HTTP request in Node.js?

An HTTP request is a message sent by a client, such as a browser, to a server. It contains information such as the requested URL, HTTP method, headers, and sometimes request data.

In Node.js, this information is available through the req object.

2. What is an HTTP response in Node.js?

An HTTP response is the information sent by the server back to the client after processing a request.

The res object is used to create the response.

For example:

res.end("Hello World");

3. What is the difference between req and res?

req represents the incoming request from the client.

req.url
req.method
req.headers

res represents the outgoing response from the server.

res.statusCode
res.setHeader()
res.end()

4. How do I get the requested URL in Node.js?

Use:

console.log(req.url);

For example, if the user visits:

http://localhost:3000/about

then:

req.url

contains:

/about

5. How do I get the HTTP method of a request?

Use:

console.log(req.method);

For a normal browser page request, the value will commonly be:

GET

Other HTTP methods include POST, PUT, PATCH, and DELETE.

6. How do I send JSON in an HTTP response?

Set the content type to JSON and use JSON.stringify():

const data = {
    name: "Riya",
    age: 18
};

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

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

7. What does res.end() do?

res.end() finishes the HTTP response. It can also send the final response data.

res.end("Response completed.");

A response should eventually be ended so that the client knows that the server has finished sending the response.

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

Scroll to Top