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
- Import the
httpmodule. - Create the server.
- The
reqobject represents the incoming request. req.urlcontains the requested URL.- Display the URL in the terminal.
- 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
req.methodcontains the HTTP request method.- Browser page requests normally use
GET. - Store or use the method as needed.
- 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
- HTTP requests contain headers.
- Node.js makes request headers available through
req.headers. "user-agent"identifies information about the client or browser.- Use bracket notation to access the header.
- 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
- Create the HTTP server.
- Use
res.setHeader()to create a response header. - The first argument is the header name.
- The second argument is the header value.
- 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
- Check the requested URL.
- If it is
/, set the status to200. - Otherwise, set the status to
404. - 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
- Create the server.
- Set status code
200. - Set
Content-Typetotext/html. - Create HTML content.
- 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
- Create a JavaScript object.
- Set the response status to
200. - Set
Content-Typetoapplication/json. - Convert the object into JSON using
JSON.stringify(). - 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
- Import
http. - Import the
URLclass. - Create a URL object from the request.
- Access
searchParams. - Use
.get("name")to read the query parameter. - Check whether a name was provided.
- 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
- Check
req.method. - If it is
GET, send the GET response. - If it is
POST, send the POST response. - For unsupported methods, return status
405. 405means 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
404for 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
- Create an HTTP server.
- Log the incoming request method and URL.
- Check whether the request uses
GET. - Return
405if another method is used. - Check the requested URL.
- Return HTML for
/. - Return HTML for
/about. - Return JSON for
/api/student. - Return
404for an unknown route. - Set the appropriate
Content-Type. - Set the appropriate HTTP status code.
- 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
reqobject. - Node.js provides response methods through the
resobject. req.urlgives you the requested URL.req.methodgives you the HTTP request method.req.headerscontains incoming request headers.res.setHeader()creates or modifies a response header.res.writeHead()can set status codes and headers together.res.statusCodeallows you to set the response status.res.end()finishes the response.Content-Typetells 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
URLandsearchParams. 404means the requested resource was not found.405means 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.
