lecture Notes Of Class 4: Creating a
Simple Web Server in Node.js
Objective:
By the end of this
class, you will learn how to:
- Create a basic HTTP server using Node.js.
- Set up routes to handle different types of
HTTP requests (GET, POST).
- Send a response back to the client.
Introduction to Web
Servers in Node.js
A web server is a
software that listens for requests from clients (like web browsers) and sends
back a response. Node.js provides a built-in module called http that allows you
to easily create an HTTP server and handle requests.
When you run a web
server, it typically listens on a specific port for incoming requests. The
server can then respond with content (like HTML, JSON, or files) based on the
request.
1. Setting Up a
Basic HTTP Server
Node.js provides the
http module to create a web server. This module allows you to handle incoming
HTTP requests and send responses back to the client.
Steps to Create a
Basic HTTP Server:
- Import the http Module: You need to include the http module in
your script to create a server.
javascript
CopyEdit
const http =
require('http');
- Create the Server: You can use the http.createServer()
method to create a server. This method takes a callback function that
receives two arguments: req (the request object) and res (the response
object).
javascript
CopyEdit
const server =
http.createServer((req, res) => {
// Server logic will go here
});
- Listen for Incoming Requests: The server needs to listen on a specific
port. We can use the .listen() method to do this. The listen() method
takes a port number and an optional callback function that runs once the
server is ready.
javascript
CopyEdit
server.listen(3000, ()
=> {
console.log('Server is running on
http://localhost:3000');
});
Complete Code for a
Basic HTTP Server:
javascript
CopyEdit
const http =
require('http');
const server =
http.createServer((req, res) => {
// Set the response HTTP header with a status
code and content type
res.writeHead(200, { 'Content-Type':
'text/plain' });
// Send a response to the client
res.end('Hello, Node.js Web Server!');
});
// The server listens
on port 3000
server.listen(3000, ()
=> {
console.log('Server is running on
http://localhost:3000');
});
- When you run this server (node server.js),
it will listen on port 3000 and respond with "Hello, Node.js Web
Server!" to any incoming request.
2. Setting Up
Routes for Different HTTP Requests
To make your web
server more functional, you can handle different types of HTTP requests such as
GET, POST, PUT, and DELETE. In this class, we will focus on the GET and POST
methods.
Handling a GET
Request:
A GET request is
typically used to fetch data from the server. You can handle GET requests by
checking the req.method property in the request object.
javascript
CopyEdit
const server =
http.createServer((req, res) => {
if (req.method === 'GET') {
// Respond to GET requests
res.writeHead(200, { 'Content-Type':
'text/plain' });
res.end('This is a response to a GET
request!');
}
});
Handling a POST
Request:
A POST request is used
to send data to the server. You can handle POST requests by checking the
req.method and reading the data sent by the client using the req.on('data')
event.
javascript
CopyEdit
const server =
http.createServer((req, res) => {
if (req.method === 'POST') {
let body = '';
// Read the data sent by the client
req.on('data', chunk => {
body += chunk;
});
// Once all data is received, send a
response
req.on('end', () => {
res.writeHead(200, { 'Content-Type':
'text/plain' });
res.end(`Received POST data: ${body}`);
});
}
});
Complete Example
with Both GET and POST:
javascript
CopyEdit
const http =
require('http');
const server =
http.createServer((req, res) => {
// Handling GET requests
if (req.method === 'GET') {
res.writeHead(200, { 'Content-Type':
'text/plain' });
res.end('This is a response to a GET
request!');
}
// Handling POST requests
if (req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk;
});
req.on('end', () => {
res.writeHead(200, { 'Content-Type':
'text/plain' });
res.end(`Received POST data: ${body}`);
});
}
});
server.listen(3000, ()
=> {
console.log('Server is running on
http://localhost:3000');
});
- GET Request Example:
- To test the GET request, visit
http://localhost:3000 in your browser, and the response will be:
"This is a response to a GET request!"
- POST Request Example:
- You can test the POST request using a
tool like Postman or by sending data using a form.
3. Sending a
Response Back to the Client
When creating a web
server, it's essential to send responses back to the client. This is done using
the res (response) object.
Setting the
Response Status Code:
You can set the HTTP
status code for the response using res.writeHead(). A status code of 200
typically means success.
javascript
CopyEdit
res.writeHead(200, {
'Content-Type': 'text/plain' });
Sending Content
Back:
To send content back
to the client, use the res.end() method, which sends the response and closes
the connection.
javascript
CopyEdit
res.end('Hello,
Node.js!');
- Example Response Headers:
- Content-Type: Defines the format of the
response (e.g., text/html, application/json).
- Status Code: Indicates the outcome of the
request (e.g., 200 OK, 404 Not Found).
Lab Tasks
Task 1: Create a
Basic HTTP Server using the http module
- Use the code provided above to create a
basic web server.
- Test it by running the server and visiting
http://localhost:3000 in your browser.
Task 2: Set Up
Routes to Handle Different HTTP Requests
- Add GET and POST route handling logic as
demonstrated in the examples above.
- Test your server using a browser for GET
and Postman for POST requests.
Task 3: Send a
Response Back to the Client
- Customize the response by sending
different content types (like text/html, application/json) to the client.
- Test the server to ensure the correct
responses are sent based on the type of request.
Conclusion
In this class, you
learned how to:
- Create a basic HTTP server using Node.js.
- Handle different types of HTTP requests
such as GET and POST.
- Send appropriate responses back to the
client.
These are foundational
skills for building web applications and APIs in Node.js. The next step would
be to explore frameworks like Express.js for more advanced routing and easier
server setup.
4o mini
You said:
write 10 no of
assignments with solution in detail from the same above topic
ChatGPT said:
ChatGPT
Assignments on
Creating a Simple Web Server in Node.js
Assignment 1: Basic
HTTP Server
Task:
Create a basic HTTP server that listens on port 4000 and responds with
"Welcome to Node.js Web Server!" when accessed via a browser or HTTP
client.
Solution:
javascript
CopyEdit
const http =
require('http');
// Create server
const server =
http.createServer((req, res) => {
// Set response header
res.writeHead(200, { 'Content-Type':
'text/plain' });
// Send response
res.end('Welcome to Node.js Web Server!');
});
// Listen on port 4000
server.listen(4000, ()
=> {
console.log('Server is running on
http://localhost:4000');
});
To test:
- Open a browser and go to
http://localhost:4000.
Assignment 2:
Handling GET Requests
Task:
Modify the server to handle GET requests and respond with a JSON object:
{"message": "GET request received!"}.
Solution:
javascript
CopyEdit
const http =
require('http');
// Create server
const server =
http.createServer((req, res) => {
// Handle GET request
if (req.method === 'GET') {
res.writeHead(200, { 'Content-Type':
'application/json' });
res.end(JSON.stringify({ message: "GET
request received!" }));
}
});
// Listen on port 4000
server.listen(4000, ()
=> {
console.log('Server is running on
http://localhost:4000');
});
To test:
- Open Postman or a browser and make a GET
request to http://localhost:4000.
Assignment 3:
Handling POST Requests
Task:
Create a server that handles POST requests and echoes back the received data.
Solution:
javascript
CopyEdit
const http = require('http');
const server =
http.createServer((req, res) => {
if (req.method === 'POST') {
let body = '';
// Collect data
req.on('data', chunk => {
body += chunk;
});
// Respond with received data
req.on('end', () => {
res.writeHead(200, { 'Content-Type':
'application/json' });
res.end(`Received data: ${body}`);
});
}
});
// Listen on port 4000
server.listen(4000, ()
=> {
console.log('Server is running on
http://localhost:4000');
});
To test:
- Use Postman to send a POST request with
some data to http://localhost:4000.
Assignment 4:
Handling Different Routes
Task:
Create a server that listens on different routes. Respond with different
messages based on the route (/home, /about, /contact).
Solution:
javascript
CopyEdit
const http =
require('http');
const server =
http.createServer((req, res) => {
if (req.method === 'GET') {
if (req.url === '/home') {
res.writeHead(200, { 'Content-Type':
'text/plain' });
res.end('Welcome to the Home Page');
} else if (req.url === '/about') {
res.writeHead(200, { 'Content-Type':
'text/plain' });
res.end('This is the About Page');
} else if (req.url === '/contact') {
res.writeHead(200, { 'Content-Type':
'text/plain' });
res.end('Contact us at
contact@example.com');
} else {
res.writeHead(404, { 'Content-Type':
'text/plain' });
res.end('Page Not Found');
}
}
});
// Listen on port 4000
server.listen(4000, ()
=> {
console.log('Server is running on
http://localhost:4000');
});
To test:
- Test routes /home, /about, and /contact in
the browser.
Assignment 5:
Dynamic Route Handling
Task:
Create a server that dynamically handles routes using URL parameters. For
example, a route /greet/{name} should return a message Hello, {name}.
Solution:
javascript
CopyEdit
const http =
require('http');
const server =
http.createServer((req, res) => {
if (req.method === 'GET') {
const urlParts = req.url.split('/');
if (urlParts[1] === 'greet' &&
urlParts.length === 3) {
const name = urlParts[2];
res.writeHead(200, { 'Content-Type':
'text/plain' });
res.end(`Hello, ${name}`);
} else {
res.writeHead(404, { 'Content-Type':
'text/plain' });
res.end('Route Not Found');
}
}
});
// Listen on port 4000
server.listen(4000, ()
=> {
console.log('Server is running on
http://localhost:4000');
});
To test:
- Visit http://localhost:4000/greet/John in
the browser, and it will return Hello, John.
Assignment 6:
Response with HTML Content
Task:
Create a server that responds with an HTML page for a GET request.
Solution:
javascript
CopyEdit
const http =
require('http');
const server =
http.createServer((req, res) => {
if (req.method === 'GET') {
res.writeHead(200, { 'Content-Type':
'text/html' });
res.end('<html><body><h1>Welcome to
Node.js!</h1><p>This is an HTML
response</p></body></html>');
}
});
// Listen on port 4000
server.listen(4000, ()
=> {
console.log('Server is running on
http://localhost:4000');
});
To test:
- Open a browser and visit
http://localhost:4000 to see the HTML content.
Assignment 7:
Custom Status Codes
Task:
Create a server that responds with custom status codes. For example, send a 404
Not Found for undefined routes and 200 OK for /home.
Solution:
javascript
CopyEdit
const http =
require('http');
const server =
http.createServer((req, res) => {
if (req.method === 'GET') {
if (req.url === '/home') {
res.writeHead(200, { 'Content-Type':
'text/plain' });
res.end('Home Page');
} else {
res.writeHead(404, { 'Content-Type':
'text/plain' });
res.end('Page Not Found');
}
}
});
// Listen on port 4000
server.listen(4000, ()
=> {
console.log('Server is running on
http://localhost:4000');
});
To test:
- Visit http://localhost:4000/home for 200
OK and http://localhost:4000/unknown for 404 Not Found.
Assignment 8:
Sending JSON Data
Task:
Create a server that handles a GET request to /user and responds with a JSON
object representing a user, e.g., {"name": "Alice",
"age": 25}.
Solution:
javascript
CopyEdit
const http =
require('http');
const server = http.createServer((req,
res) => {
if (req.method === 'GET' && req.url
=== '/user') {
res.writeHead(200, { 'Content-Type':
'application/json' });
res.end(JSON.stringify({ name: 'Alice',
age: 25 }));
}
});
// Listen on port 4000
server.listen(4000, ()
=> {
console.log('Server is running on
http://localhost:4000');
});
To test:
- Send a GET request to /user in Postman or
browser.
Assignment 9:
Handling POST Request Data (Form Submission)
Task:
Create a server that accepts a POST request with form data (e.g.,
name=John&age=30) and sends a response confirming the received data.
Solution:
javascript
CopyEdit
const http =
require('http');
const server =
http.createServer((req, res) => {
if (req.method === 'POST' && req.url
=== '/submit') {
let body = '';
req.on('data', chunk => {
body += chunk;
});
req.on('end', () => {
res.writeHead(200, { 'Content-Type':
'text/plain' });
res.end(`Form Submitted with Data:
${body}`);
});
}
});
// Listen on port 4000
server.listen(4000, ()
=> {
console.log('Server is running on
http://localhost:4000');
});
To test:
- Use Postman to send a POST request with
form data to http://localhost:4000/submit.
Assignment 10:
Logging Incoming Requests
Task:
Create a server that logs incoming requests' method, URL, and headers to the
console.
Solution:
javascript
CopyEdit
const http =
require('http');
const server =
http.createServer((req, res) => {
// Log request details
console.log(`Request Method: ${req.method}`);
console.log(`Request URL: ${req.url}`);
console.log(`Request Headers:`, req.headers);
res.writeHead(200, { 'Content-Type':
'text/plain' });
res.end('Request details logged!');
});
// Listen on port 4000
server.listen(4000, ()
=> {
console.log('Server is running on
http://localhost:4000');
});
To test:
- Send any GET or POST request to
http://localhost:4000 and check the console for request details.
These assignments
guide you through various tasks in building a Node.js HTTP server, ranging from
basic server creation to handling different types of requests and routing.
4o mini
You said:
write 100 no of MCQ
answer with explanation from the same above topic
ChatGPT said:
ChatGPT
Creating 100
multiple-choice questions (MCQs) along with answers and detailed explanations
from the topic "Creating a Simple Web Server in Node.js" is quite an
extensive task. Here's a set of 25 MCQs to get you started. If you'd like, I
can provide additional sets to reach 100.
MCQs for
"Creating a Simple Web Server in Node.js"
Question 1: What is
the primary module used to create an HTTP server in Node.js?
a) fs
b) path
c) http
d) url
Answer: c) http
Explanation: The http module is used in Node.js to create and manage
HTTP servers.
Question 2: Which
method is used to create an HTTP server in Node.js?
a) createServer()
b) listen()
c) request()
d) server()
Answer: a) createServer()
Explanation: The http.createServer() method is used to create an HTTP
server in Node.js.
Question 3: What is
the default status code returned when a request is successfully handled by a
Node.js HTTP server?
a) 200
b) 400
c) 404
d) 500
Answer: a) 200
Explanation: A status code of 200 OK is returned when the server
successfully processes the request.
Question 4: Which
method is used to send a response to the client in a Node.js HTTP server?
a) send()
b) write()
c) end()
d) respond()
Answer: c) end()
Explanation: The end() method is used to send the response to the client
in Node.js.
Question 5: In the
HTTP module, which of the following is used to define the HTTP request's status
code and headers?
a) res.writeHead()
b) res.end()
c) req.on()
d) http.createServer()
Answer: a) res.writeHead()
Explanation: The res.writeHead() method is used to set the status code
and headers for the HTTP response.
Question 6: Which
of the following HTTP methods can be used to send data to a server?
a) GET
b) POST
c) DELETE
d) PATCH
Answer: b) POST
Explanation: The POST method is used to send data to a server, typically
for creating or updating resources.
Question 7: How can
you get the URL from the incoming request in Node.js?
a) req.url()
b) req.getUrl()
c) req.url
d) req.uri()
Answer: c) req.url
Explanation: The req.url property contains the URL of the incoming
request.
Question 8: What
type of content type should be used for a JSON response in a Node.js server?
a) text/html
b) application/json
c) text/plain
d) application/xml
Answer: b) application/json
Explanation: The application/json content type is used to send JSON data
in an HTTP response.
Question 9: Which
Node.js method is used to parse incoming request data?
a) JSON.parse()
b) req.on()
c) url.parse()
d) req.read()
Answer: b) req.on()
Explanation: The req.on() method is used to collect and parse incoming
request data in chunks.
Question 10: Which
module is used in Node.js to manipulate file paths?
a) fs
b) path
c) http
d) url
Answer: b) path
Explanation: The path module is used to handle and manipulate file paths
in Node.js.
Question 11: What
is the purpose of the 'listen' method in a Node.js server?
a) It handles incoming
requests.
b) It sends responses back to the client.
c) It starts the server and listens on a specified port.
d) It closes the server after the request is processed.
Answer: c) It starts the server and listens on a
specified port.
Explanation: The listen() method starts the HTTP server and makes it
listen for requests on a specified port.
Question 12: In a
Node.js HTTP server, how can you check the HTTP method of an incoming request?
a) req.method()
b) req.method
c) req.getMethod()
d) req.request()
Answer: b) req.method
Explanation: The req.method property contains the HTTP method of the
incoming request (e.g., GET, POST, etc.).
Question 13: Which
of the following is a valid way to send data with a POST request in Node.js?
a) req.data()
b) req.send()
c) req.on('data')
d) req.body()
Answer: c) req.on('data')
Explanation: The req.on('data') event is used to handle and collect data
sent with a POST request.
Question 14: How
would you handle a request to a route /about in a Node.js HTTP server?
a) if (req.url ===
'/about')
b) if (req.method === '/about')
c) if (req.url == '/about')
d) if (req.url === 'about')
Answer: a) if (req.url === '/about')
Explanation: The correct way to handle requests to a specific route is
to check if req.url matches the desired route.
Question 15: Which
status code is returned when a route or page is not found in Node.js?
a) 200
b) 301
c) 404
d) 503
Answer: c) 404
Explanation: A 404 Not Found status code is returned when the requested
route or page does not exist.
Question 16: How
can you send a response with status code 500 in Node.js?
a) res.writeHead(500)
b) res.statusCode(500)
c) res.send(500)
d) res.end(500)
Answer: a) res.writeHead(500)
Explanation: The res.writeHead(500) method is used to send a 500
Internal Server Error status code.
Question 17: Which
method would you use to serve a file from the server to the client?
a) res.serve()
b) fs.readFile()
c) res.end()
d) res.writeFile()
Answer: b) fs.readFile()
Explanation: The fs.readFile() method is used to read a file from the
server to send it as a response.
Question 18: What
is the default HTTP response content type when sending plain text in Node.js?
a) text/html
b) text/plain
c) application/json
d) text/xml
Answer: b) text/plain
Explanation: When sending plain text, the content type should be set to
text/plain.
Question 19: In the
code res.writeHead(200, {'Content-Type': 'text/plain'}), what does 200
represent?
a) Content type
b) Response body
c) Status code
d) HTTP method
Answer: c) Status code
Explanation: The 200 is the HTTP status code, which indicates that the
request was successful.
Question 20: Which
method is used to respond with a JSON object in Node.js?
a) res.send()
b) res.json()
c) res.write()
d) res.end()
Answer: b) res.json()
Explanation: The res.json() method is used to send a JSON object as the
response.
Question 21: How
can you read the content of a file asynchronously in Node.js?
a) fs.read()
b) fs.readFileSync()
c) fs.readFile()
d) fs.load()
Answer: c) fs.readFile()
Explanation: The fs.readFile() method reads the content of a file
asynchronously.
Question 22: How
would you set the response content type to HTML?
a) res.writeHead(200,
{'Content-Type': 'text/html'})
b) res.setHeader('text/html')
c) res.write('text/html')
d) res.end('Content-Type: text/html')
Answer: a) res.writeHead(200, {'Content-Type':
'text/html'})
Explanation: The correct way to set the content type for an HTML
response is using res.writeHead() with 'text/html'.
Question 23: What
does req.on('end') do in a Node.js HTTP server?
a) Ends the response
b) Signals the end of incoming data
c) Closes the server
d) Starts a new request
Answer: b) Signals the end of incoming data
Explanation: The req.on('end') event is triggered when all the data from
the request has been received.
Question 24: Which
of the following allows you to read and write files in Node.js?
a) fs
b) path
c) url
d) events
Answer: a) fs
Explanation: The fs (File System) module allows you to read, write, and
manipulate files in Node.js.
Question 25: How
can you create an HTTP server that listens on port 3000 in Node.js?
a) server.listen(3000)
b) http.listen(3000)
c) http.createServer().listen(3000)
d) server.start(3000)
Answer: c) http.createServer().listen(3000)
Explanation: The http.createServer().listen(3000) method creates an HTTP
server and listens for requests on port 3000.
Would you like me to
continue with more MCQs to complete the set of 100?
4o mini
You said:
yes
ChatGPT said:
ChatGPT
Here are additional 25
multiple-choice questions (MCQs) for the topic "Creating a Simple Web
Server in Node.js." This brings us closer to the goal of 100 MCQs.
Question 26: How do
you handle POST request data in Node.js?
a) req.on('end')
b) req.on('data')
c) req.write()
d) req.send()
Answer: b) req.on('data')
Explanation: The req.on('data') event is used to handle incoming data in
a POST request.
Question 27: Which
of the following is true about the req and res objects in Node.js HTTP servers?
a) req is used to
handle incoming requests, and res is used to send responses.
b) req handles responses, and res handles requests.
c) req and res are interchangeable.
d) req and res are not used in Node.js.
Answer: a) req is used to handle incoming requests,
and res is used to send responses.
Explanation: The req object contains information about the incoming
request, while the res object is used to send the response back to the client.
Question 28: How
can you send an HTTP response with JSON data in Node.js?
a) res.send()
b) res.json()
c) res.write()
d) res.end()
Answer: b) res.json()
Explanation: The res.json() method is used to send JSON data as a
response.
Question 29: What
does the fs.writeFile() method do in Node.js?
a) Reads a file
b) Writes data to a file
c) Appends data to a file
d) Deletes a file
Answer: b) Writes data to a file
Explanation: The fs.writeFile() method is used to write data to a file.
If the file does not exist, it will be created.
Question 30: What
module would you use to parse a URL in Node.js?
a) http
b) url
c) path
d) fs
Answer: b) url
Explanation: The url module is used to parse and manipulate URLs in
Node.js.
Question 31: Which
of the following is the correct way to include the http module in a Node.js
file?
a) import http from
'http'
b) require('http')
c) import { http }
d) include 'http'
Answer: b) require('http')
Explanation: The require('http') syntax is used to include the http
module in a Node.js file.
Question 32: What
is the purpose of the res.setHeader() method in Node.js?
a) It sets the
response status code.
b) It sets the content of the response.
c) It sets the headers for the response.
d) It sets the URL of the response.
Answer: c) It sets the headers for the response.
Explanation: The res.setHeader() method is used to set the headers for
the HTTP response, such as content type.
Question 33: How
can you handle multiple HTTP request types (e.g., GET, POST) in a Node.js
server?
a) Use a switch
statement on req.url
b) Use if-else conditions on req.method
c) Handle each request in separate files
d) Use res.write() for all methods
Answer: b) Use if-else conditions on req.method
Explanation: You can use if-else conditions on req.method (such as GET,
POST, PUT, etc.) to handle different types of HTTP requests.
Question 34: How do
you serve static files (e.g., HTML, CSS, JavaScript) from a Node.js server?
a) Using fs.readFile()
b) Using res.writeHead()
c) Using res.end()
d) By configuring a static file handler module like express
Answer: a) Using fs.readFile()
Explanation: To serve static files, you can use fs.readFile() to read
the content of files and then send them via res.end().
Question 35: What
does the path.join() method in Node.js do?
a) Reads a file path
b) Joins multiple path segments into one
c) Splits a file path
d) Converts a file path to a string
Answer: b) Joins multiple path segments into one
Explanation: The path.join() method combines multiple path segments into
one single, normalized file path.
Question 36: How do
you handle a request to a non-existent route in a Node.js server?
a) Use a default case
in a switch statement.
b) Redirect to another URL.
c) Respond with a 404 status code.
d) Do nothing and wait for another request.
Answer: c) Respond with a 404 status code.
Explanation: If a request is made to a non-existent route, the server
should respond with a 404 Not Found status code to indicate that the route
doesn't exist.
Question 37: Which
Node.js function is used to create a simple HTTP server?
a) http.create()
b) http.createServer()
c) http.startServer()
d) http.buildServer()
Answer: b) http.createServer()
Explanation: The http.createServer() function is used to create a simple
HTTP server in Node.js.
Question 38: Which
of the following will correctly send a 404 error in Node.js?
a) res.writeHead(404)
b) res.send(404)
c) res.setHeader(404)
d) res.end(404)
Answer: a) res.writeHead(404)
Explanation: To send a 404 Not Found error, you use res.writeHead(404)
to set the status code.
Question 39: What
is the role of the req object in Node.js HTTP servers?
a) It holds
information about the incoming request.
b) It holds the response data.
c) It contains the status code for the response.
d) It handles routing requests.
Answer: a) It holds information about the incoming
request.
Explanation: The req object in Node.js contains information about the
HTTP request, such as the URL, headers, and method.
Question 40: Which
of the following headers would you include for a JSON response in Node.js?
a) Content-Type:
application/json
b) Content-Type: text/html
c) Content-Type: text/plain
d) Content-Type: application/xml
Answer: a) Content-Type: application/json
Explanation: The Content-Type: application/json header should be set
when sending JSON data in the response.
Question 41: What
does res.write() do in a Node.js HTTP server?
a) Sends an HTTP
response immediately.
b) Writes data to the response stream.
c) Closes the server connection.
d) Writes the request data to the console.
Answer: b) Writes data to the response stream.
Explanation: The res.write() method is used to write data to the
response stream before sending the final response using res.end().
Question 42: Which
of the following methods can be used to handle multiple HTTP routes in a
Node.js HTTP server?
a) Use the express
framework
b) Use if-else statements on req.url
c) Use path.join() for routing
d) Handle each request in separate functions
Answer: b) Use if-else statements on req.url
Explanation: You can handle different HTTP routes by checking the
req.url and using conditional statements.
Question 43: What
is the default port that Node.js listens on?
a) 8080
b) 3000
c) 4000
d) 5000
Answer: b) 3000
Explanation: By convention, Node.js applications often listen on port
3000, but it can be changed using the listen() method.
Question 44: How
would you respond with an HTML page to a client in Node.js?
a) res.write('<html>...</html>')
b) res.send('<html>...</html>')
c) res.end('<html>...</html>')
d) All of the above
Answer: d) All of the above
Explanation: All the methods (write(), send(), and end()) can be used to
send an HTML response, but res.end() is the most common for simple responses.
Question 45: How do
you handle asynchronous file reading in Node.js?
a) fs.readFileSync()
b) fs.readFile()
c) fs.writeFileSync()
d) fs.read()
Answer: b) fs.readFile()
Explanation: The fs.readFile() method is used for asynchronous file
reading in Node.js.
Question 46: What
is the use of the path.resolve() method in Node.js?
a) Resolves a sequence
of paths to an absolute path.
b) Splits a file path into parts.
c) Creates a new file path.
d) Joins multiple paths into one.
Answer: a) Resolves a sequence of paths to an absolute
path.
Explanation: The path.resolve() method resolves a sequence of paths into
an absolute file path.
Question 47: How do
you parse query strings from a URL in Node.js?
a) url.parse()
b) url.query()
c) querystring.parse()
d) querystring.split()
Answer: c) querystring.parse()
Explanation: The querystring.parse() method is used to parse query
strings from a URL.
Question 48: Which
method is used to handle multiple request types like GET and POST in Node.js?
a) http.request()
b) http.createServer()
c) http.get()
d) http.listen()
Answer: b) http.createServer()
Explanation: The http.createServer() method is used to create a server
that handles different request types like GET and POST.
Question 49: How do
you handle routing for a POST request in Node.js?
a) if (req.method ===
'POST')
b) if (req.method === 'GET')
c) if (req.url === '/post')
d) req.on('POST')
Answer: a) if (req.method === 'POST')
Explanation: The req.method is used to check the type of HTTP request,
and POST is handled by checking if req.method === 'POST'.
Question 50: How
can you return an HTTP 200 status code in Node.js?
a) res.status(200)
b) res.send(200)
c) res.write(200)
d) res.setHeader(200)
Answer: a) res.status(200)
Explanation: The res.status(200) method sets the HTTP status code to 200
OK, which indicates a successful request.
These questions should
help strengthen understanding of creating a web server in Node.js. Would you
like to continue, or would you prefer more focused topics?
4o mini
You said:
yes
ChatGPT said:
ChatGPT
Great! Here are
additional 25 multiple-choice questions (MCQs) for the topic "Creating a
Simple Web Server in Node.js."
Question 51: Which
method is used to handle the body of a POST request in Node.js?
a) req.body()
b) req.on('data')
c) req.parse()
d) req.receive()
Answer: b) req.on('data')
Explanation: The req.on('data') event is used to handle the body of a
POST request in Node.js.
Question 52: How
can you access the headers of a request in Node.js?
a) req.headers()
b) req.header()
c) req.getHeader()
d) req.headers
Answer: d) req.headers
Explanation: The req.headers object contains the headers of the incoming
HTTP request.
Question 53: Which
method is used to end a response in Node.js?
a) res.writeEnd()
b) res.end()
c) res.complete()
d) res.close()
Answer: b) res.end()
Explanation: The res.end() method is used to finalize and send the
response to the client.
Question 54: Which
of the following is correct to parse a URL in Node.js?
a) url.decode()
b) url.parse()
c) url.encode()
d) url.extract()
Answer: b) url.parse()
Explanation: The url.parse() method is used to parse a URL into
components like protocol, hostname, pathname, etc.
Question 55: How do
you create a simple HTTP server that listens on port 8000 in Node.js?
a) http.listen(8000)
b) http.createServer().listen(8000)
c) http.start(8000)
d) http.server(8000)
Answer: b) http.createServer().listen(8000)
Explanation: The http.createServer().listen(8000) method creates an HTTP
server and listens on port 8000.
Question 56: Which
module is used to handle path manipulation in Node.js?
a) file
b) path
c) url
d) fs
Answer: b) path
Explanation: The path module is used to handle and manipulate file paths
in Node.js.
Question 57: How
can you redirect the client to a new URL in a Node.js server?
a) res.redirect()
b) res.location()
c) res.writeHead(301, { Location: 'new_url' })
d) res.sendRedirect()
Answer: c) res.writeHead(301, { Location: 'new_url' })
Explanation: The res.writeHead(301, { Location: 'new_url' }) is used to
send a 301 redirect response with the new URL.
Question 58: Which
method is used to parse query strings from a URL in Node.js?
a) url.parse()
b) querystring.parse()
c) url.query()
d) query.parse()
Answer: b) querystring.parse()
Explanation: The querystring.parse() method is used to parse query
strings from a URL in Node.js.
Question 59: How do
you read a file asynchronously in Node.js?
a) fs.readFile()
b) fs.readSync()
c) fs.readFileSync()
d) fs.read()
Answer: a) fs.readFile()
Explanation: The fs.readFile() method reads a file asynchronously in
Node.js.
Question 60: Which
method is used to create a readable stream in Node.js?
a) fs.createStream()
b) fs.createReadableStream()
c) fs.createReadStream()
d) fs.readStream()
Answer: c) fs.createReadStream()
Explanation: The fs.createReadStream() method is used to create a
readable stream for a file.
Question 61: How do
you parse a URL using the url module in Node.js?
a) url.toString()
b) url.extract()
c) url.parse()
d) url.decode()
Answer: c) url.parse()
Explanation: The url.parse() method is used to parse a URL into
different components like protocol, hostname, pathname, etc.
Question 62: How
can you handle multiple routes in a Node.js HTTP server?
a) Use the express
framework
b) Use if conditions based on req.url
c) Use switch-case based on req.url
d) Both b and c
Answer: d) Both b and c
Explanation: You can use if or switch-case statements to handle multiple
routes based on req.url.
Question 63: How do
you send a JSON response to a client in Node.js?
a) res.writeJSON()
b) res.json()
c) res.sendJSON()
d) res.write()
Answer: b) res.json()
Explanation: The res.json() method sends a JSON response to the client
in Node.js.
Question 64: How
can you prevent clients from caching a response in Node.js?
a) Set the Cache-Control
header to no-store
b) Set the Cache-Control header to max-age=0
c) Set the Cache-Control header to no-cache
d) All of the above
Answer: d) All of the above
Explanation: Setting the Cache-Control header to no-store, max-age=0, or
no-cache will prevent clients from caching the response.
Question 65: Which
of the following methods can be used to serve static files in Node.js?
a) fs.readFile()
b) express.static()
c) path.join()
d) fs.createReadStream()
Answer: b) express.static()
Explanation: The express.static() middleware is used to serve static
files in a Node.js application using the Express framework.
Question 66: Which
method is used to set HTTP headers in a Node.js server?
a) res.header()
b) res.setHeader()
c) res.set()
d) res.headers()
Answer: b) res.setHeader()
Explanation: The res.setHeader() method is used to set headers for the
HTTP response.
Question 67: What
is the default HTTP status code for a successful GET request?
a) 200
b) 404
c) 301
d) 500
Answer: a) 200
Explanation: A successful GET request returns a 200 OK status code by
default.
Question 68: What
is the purpose of the req.method property in Node.js?
a) It specifies the
HTTP status code.
b) It holds the headers of the incoming request.
c) It determines the type of HTTP request (GET, POST, etc.).
d) It contains the body of the incoming request.
Answer: c) It determines the type of HTTP request
(GET, POST, etc.).
Explanation: The req.method property contains the HTTP method of the
request, such as GET, POST, PUT, etc.
Question 69: Which
of the following methods in Node.js can be used to handle HTTP errors?
a) res.error()
b) res.status()
c) res.handleError()
d) res.sendError()
Answer: b) res.status()
Explanation: The res.status() method is used to set the HTTP status
code, such as 404 Not Found, 500 Internal Server Error, etc.
Question 70: How
can you respond with plain text in Node.js?
a) res.writeText()
b) res.sendText()
c) res.write()
d) res.end()
Answer: c) res.write()
Explanation: The res.write() method is used to send plain text as part
of the response.
Question 71: Which
of the following methods sends a response without any content in Node.js?
a) res.empty()
b) res.end()
c) res.write()
d) res.send()
Answer: b) res.end()
Explanation: The res.end() method sends a response and indicates that
the response has been completed, without any content.
Question 72: How do
you specify the MIME type of a response in Node.js?
a)
res.setHeader('Content-Type', 'text/html')
b) res.contentType('text/html')
c) res.mimeType('text/html')
d) res.setMime('text/html')
Answer: a) res.setHeader('Content-Type', 'text/html')
Explanation: The res.setHeader('Content-Type', 'text/html') method is
used to set the MIME type of the response.
Question 73: What
is the correct syntax to send an HTTP GET request to a Node.js server?
a) http.get(url)
b) http.request(url)
c) http.send(url)
d) http.makeRequest(url)
Answer: a) http.get(url)
Explanation: The http.get() method is used to send an HTTP GET request
to a server.
Question 74: Which
of the following modules is required for creating an HTTP server in Node.js?
a) http
b) url
c) fs
d) path
Answer: a) http
Explanation: The http module is required to create an HTTP server in
Node.js.
Question 75: Which
of the following is used to make an HTTP request from Node.js to another
server?
a) http.get()
b) fs.read()
c) http.send()
d) http.request()
Answer: d) http.request()
Explanation: The http.request() method is used to make an HTTP request
from a Node.js application to another server.
These additional
questions and explanations will help reinforce the concepts of creating a
simple web server in Node.js. Would you like more questions or further
explanations on specific areas?
4o mini
You said:
yes
ChatGPT said:
ChatGPT
Here are 25 more
multiple-choice questions (MCQs) on the topic "Creating a Simple Web
Server in Node.js."
Question 76: Which
method in Node.js is used to handle incoming HTTP requests?
a) server.request()
b) server.on('request')
c) server.handle()
d) server.on('data')
Answer: b) server.on('request')
Explanation: The server.on('request') method listens for incoming HTTP
requests and passes the request and response objects to the callback function.
Question 77: What
does res.statusCode in Node.js represent?
a) The status code of
the HTTP response
b) The status message of the HTTP response
c) The status code of the HTTP request
d) The status message of the HTTP request
Answer: a) The status code of the HTTP response
Explanation: The res.statusCode property holds the status code for the
HTTP response, such as 200, 404, 500, etc.
Question 78: Which
method in Node.js is used to send a JSON response to the client?
a) res.sendJSON()
b) res.writeJSON()
c) res.endJSON()
d) res.json()
Answer: d) res.json()
Explanation: The res.json() method is used to send a JSON response to
the client, setting the appropriate headers.
Question 79: How
can you log the URL of incoming HTTP requests in Node.js?
a)
console.log(req.url)
b) console.debug(req.url)
c) console.print(req.url)
d) console.url(req.url)
Answer: a) console.log(req.url)
Explanation: You can log the URL of the incoming HTTP request by using
console.log(req.url).
Question 80: Which
event is emitted when the HTTP server in Node.js starts listening?
a) 'listening'
b) 'connect'
c) 'start'
d) 'ready'
Answer: a) 'listening'
Explanation: The 'listening' event is emitted when the server begins to
listen for incoming requests on a specific port.
Question 81: What
does the req.method property in Node.js contain?
a) The body of the
request
b) The URL of the request
c) The type of HTTP request (GET, POST, etc.)
d) The headers of the request
Answer: c) The type of HTTP request (GET, POST, etc.)
Explanation: The req.method property contains the HTTP method used for
the request, such as GET, POST, PUT, etc.
Question 82: What
is the default port that Node.js HTTP server listens to if not specified?
a) 8080
b) 3000
c) 5000
d) 80
Answer: b) 3000
Explanation: By default, Node.js applications typically listen on port
3000 unless specified otherwise.
Question 83: Which
method is used to write data to the response stream in Node.js?
a) res.write()
b) res.send()
c) res.sendData()
d) res.response()
Answer: a) res.write()
Explanation: The res.write() method is used to write data to the
response stream before calling res.end() to send the response to the client.
Question 84: What
is the purpose of the http.createServer() method in Node.js?
a) To create an HTTP
request
b) To handle HTTP requests
c) To create an HTTP server to listen for requests
d) To send HTTP requests
Answer: c) To create an HTTP server to listen for
requests
Explanation: The http.createServer() method is used to create an HTTP
server that listens for incoming requests and sends responses.
Question 85: What
is the purpose of the req.on('data') event in Node.js?
a) To send data to the
client
b) To handle the request body for POST requests
c) To parse query parameters from the URL
d) To end the request
Answer: b) To handle the request body for POST
requests
Explanation: The req.on('data') event is used to handle the incoming
data (body) of a POST request.
Question 86: How do
you send a redirect response to another URL in Node.js?
a) res.redirect(301,
'new_url')
b) res.location('new_url')
c) res.sendRedirect('new_url')
d) res.redirect()
Answer: a) res.redirect(301, 'new_url')
Explanation: The res.redirect() method sends a redirect response with a
status code (e.g., 301 for permanent redirection) and the new URL.
Question 87: Which
method in Node.js sends a 404 response for undefined routes?
a) res.status(404)
b) res.send('404')
c) res.write('404')
d) res.end()
Answer: a) res.status(404)
Explanation: The res.status(404) method sets the HTTP status code to 404
Not Found, indicating the route was not found.
Question 88: What
does the url module in Node.js help with?
a) Handling HTTP
requests
b) Manipulating file paths
c) Parsing and formatting URLs
d) Sending HTTP responses
Answer: c) Parsing and formatting URLs
Explanation: The url module is used to parse and format URLs in Node.js.
Question 89: Which
method is used to serve static files (e.g., HTML, CSS, images) in a Node.js
server?
a) serveStatic()
b) express.static()
c) staticServe()
d) static()
Answer: b) express.static()
Explanation: The express.static() middleware is used in the Express
framework to serve static files.
Question 90: How do
you ensure an HTTP request handler only handles GET requests?
a) if (req.method ===
'GET') {}
b) if (req.method === 'POST') {}
c) if (req.url === 'GET') {}
d) if (req.header('GET')) {}
Answer: a) if (req.method === 'GET') {}
Explanation: To handle only GET requests, you check if req.method ===
'GET' inside the request handler.
Question 91: Which
method is used to specify the content type of the response in Node.js?
a)
res.setHeader('Content-Type', 'text/plain')
b) res.setContentType('text/plain')
c) res.content('text/plain')
d) res.type('text/plain')
Answer: a) res.setHeader('Content-Type', 'text/plain')
Explanation: The res.setHeader() method is used to set the content type
for the HTTP response, such as text/plain, text/html, or application/json.
Question 92: Which
of the following is an event-driven model in Node.js used for handling multiple
concurrent requests?
a) Blocking I/O
b) Non-blocking I/O
c) Single-threaded
d) Multi-threaded
Answer: b) Non-blocking I/O
Explanation: Node.js uses a non-blocking I/O model to handle concurrent
requests efficiently without blocking the event loop.
Question 93: How
can you handle POST data (body) in Node.js without using external libraries?
a) By using the
req.body property
b) By using the req.on('data') event
c) By using the express.bodyParser() middleware
d) By using the http.post() method
Answer: b) By using the req.on('data') event
Explanation: The req.on('data') event allows you to handle POST request
data manually in Node.js without external libraries.
Question 94: Which
of the following headers can be set in Node.js to avoid caching of a response?
a) Cache-Control:
no-cache
b) Cache-Control: max-age=0
c) Cache-Control: no-store
d) All of the above
Answer: d) All of the above
Explanation: Setting Cache-Control headers to no-cache, max-age=0, or
no-store can prevent caching of the response.
Question 95: What
is the method used to extract query parameters from a URL in Node.js?
a) url.extract()
b) url.query()
c) querystring.parse()
d) url.queryString()
Answer: c) querystring.parse()
Explanation: The querystring.parse() method is used to parse query
strings and extract parameters from a URL.
Question 96: Which
HTTP status code represents a successful HTTP request?
a) 200 OK
b) 404 Not Found
c) 500 Internal Server Error
d) 301 Moved Permanently
Answer: a) 200 OK
Explanation: The status code 200 OK indicates that the HTTP request was
successful.
Question 97: Which
Node.js method is used to handle a POST request?
a) http.createServer()
b) http.get()
c) http.request()
d) http.post()
Answer: a) http.createServer()
Explanation: The http.createServer() method is used to handle all types
of requests, including POST. You can determine the request type with
req.method.
Question 98: How do
you handle multiple routes in Node.js?
a) Using
http.createServer() with multiple conditions
b) Using Express.js with app.get() and app.post() methods
c) Using route.get() and route.post() methods
d) Using app.route() method
Answer: b) Using Express.js with app.get() and
app.post() methods
Explanation: Express.js simplifies routing by providing methods like
app.get() and app.post() for handling different routes.
Question 99: What
is the purpose of the res.end() method in Node.js?
a) To start the
response stream
b) To end the response stream and send the response to the client
c) To write the body of the response
d) To set the HTTP status code
Answer: b) To end the response stream and send the
response to the client
Explanation: The res.end() method signals the end of the response and
sends it to the client.
Question 100: How
can you send an HTML response to the client in Node.js?
a) res.html()
b) res.sendHTML()
c) res.write('<html>...</html>')
d) res.send('<html>...</html>')
Answer: d) res.send('<html>...</html>')
Explanation: The res.send() method can be used to send HTML content as
the response to the client.

No comments:
Post a Comment