Lecture Notes Of Class 30: Building a Complete Application with
Node.js
Objective:
The goal of this class is to help you
integrate all the concepts learned throughout the course to build a complete
and functional Node.js application. By the end of this class, you will
understand how to combine different features such as CRUD operations, authentication,
and API routes into a working Node.js application.
1. Project Design
Before we start coding, it's crucial to
design the structure of your application. A well-designed project will save
time in development and ensure that your application is scalable and
maintainable.
Example Project: A Simple To-Do Application
Let’s choose a To-Do
app as a simple yet functional project to implement. A To-Do
application allows users to create, read, update, and delete tasks.
Components of the To-Do App:
- User Authentication: Users should be
able to sign up and log in to access their to-do list.
- To-Do CRUD Operations: Users can create,
update, and delete their tasks.
- Task List Display: After logging in,
users can see all the tasks they have created.
- Task Completion: Users can mark
tasks as completed or pending.
2. Implementing Necessary Features
We will break down the features into smaller
parts and implement them one by one.
a. Setting Up the Project
First, initialize your Node.js project:
bashmkdir todo-appcd todo-appnpm init -y
Install necessary dependencies:
bashnpm install express mongoose bcryptjs jsonwebtoken body-parser dotenv
- express: Web framework for building APIs.
- mongoose: MongoDB ODM (Object Data
Modeling) to interact with the database.
- bcryptjs: Used to hash passwords.
- jsonwebtoken: For creating and
verifying JWT tokens for authentication.
- body-parser: Middleware to parse incoming
request bodies.
- dotenv: For loading environment
variables.
b. Setting Up the Server
Create a basic server.js
file to set up Express and connect to MongoDB.
jsconst express = require('express');const mongoose = require('mongoose');const bodyParser = require('body-parser');require('dotenv').config(); const app = express(); // Middlewareapp.use(bodyParser.json()); // Connect to MongoDBmongoose.connect(process.env.DB_URI, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log("Connected to MongoDB")) .catch(err => console.log("Database connection error", err)); // Start the serverconst PORT = process.env.PORT || 3000;app.listen(PORT, () => { console.log(`Server running on port ${PORT}`);});
In your .env
file, add:
bashDB_URI=mongodb://localhost:27017/todo-app
c. User Authentication
We will create a user model and implement
JWT-based authentication.
Create a User
model to store user data:
jsconst mongoose = require('mongoose');const bcrypt = require('bcryptjs'); const userSchema = new mongoose.Schema({ username: { type: String, required: true }, email: { type: String, required: true, unique: true }, password: { type: String, required: true },}); userSchema.pre('save', async function(next) { if (!this.isModified('password')) return next(); const salt = await bcrypt.genSalt(10); this.password = await bcrypt.hash(this.password, salt); next();}); const User = mongoose.model('User', userSchema); module.exports = User;
Create a registration route:
jsconst User = require('./models/User');const jwt = require('jsonwebtoken'); app.post('/register', async (req, res) => { const { username, email, password } = req.body; try { const user = new User({ username, email, password }); await user.save(); const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, { expiresIn: '1h' }); res.status(201).json({ token }); } catch (err) { res.status(400).json({ message: 'Error registering user' }); }});
Create a login
route:
jsapp.post('/login', async (req, res) => { const { email, password } = req.body; const user = await User.findOne({ email }); if (!user) return res.status(400).json({ message: 'Invalid credentials' }); const isMatch = await bcrypt.compare(password, user.password); if (!isMatch) return res.status(400).json({ message: 'Invalid credentials' }); const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, { expiresIn: '1h' }); res.status(200).json({ token });});
Now, users can register and log in, and we’ll
generate a JWT token for each session.
d. CRUD Operations for To-Do Tasks
Now, let’s implement the CRUD functionality
for tasks. Create a Task model:
jsconst mongoose = require('mongoose'); const taskSchema = new mongoose.Schema({ title: { type: String, required: true }, description: String, completed: { type: Boolean, default: false }, user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },}); const Task = mongoose.model('Task', taskSchema); module.exports = Task;
Now, create routes for the CRUD operations:
Create Task:
jsapp.post('/tasks', async (req, res) => { const { title, description } = req.body; const userId = req.user.userId; // User is extracted from JWT try { const task = new Task({ title, description, user: userId }); await task.save(); res.status(201).json(task); } catch (err) { res.status(400).json({ message: 'Error creating task' }); }});
Get All Tasks:
jsapp.get('/tasks', async (req, res) => { const userId = req.user.userId; try { const tasks = await Task.find({ user: userId }); res.status(200).json(tasks); } catch (err) { res.status(500).json({ message: 'Error fetching tasks' }); }});
Update Task:
jsapp.put('/tasks/:id', async (req, res) => { const { title, description, completed } = req.body; try { const task = await Task.findByIdAndUpdate(req.params.id, { title, description, completed }, { new: true }); res.status(200).json(task); } catch (err) { res.status(400).json({ message: 'Error updating task' }); }});
Delete Task:
jsapp.delete('/tasks/:id', async (req, res) => { try { await Task.findByIdAndDelete(req.params.id); res.status(200).json({ message: 'Task deleted successfully' }); } catch (err) { res.status(400).json({ message: 'Error deleting task' }); }});
e. Authentication Middleware
To ensure that only logged-in users can
access tasks, create an authentication middleware to verify the JWT token:
jsconst jwt = require('jsonwebtoken'); const authenticate = (req, res, next) => { const token = req.header('x-auth-token'); if (!token) return res.status(401).json({ message: 'No token, authorization denied' }); try { const decoded = jwt.verify(token, process.env.JWT_SECRET); req.user = decoded; next(); } catch (err) { res.status(401).json({ message: 'Token is not valid' }); }}; app.use(authenticate); // Protect all routes below with authentication
3. Testing the Application
Testing your application is crucial to ensure
that everything works as expected. For testing, you can:
- Use Postman or Insomnia to
send requests to your API (POST, GET, PUT, DELETE).
- Test all CRUD operations and ensure
they work as expected.
- Verify that user authentication works
(you should be able to register, log in, and access tasks).
Make sure to test edge cases such as invalid
inputs, duplicate email during registration, or unauthorized access.
Conclusion
By following this approach, you have built a
simple Node.js application with the following features:
- User authentication using JWT.
- CRUD operations for managing tasks.
- A fully functional backend API.
In the next class, we can focus on improving
the app by adding more advanced features like validation, error handling, and
connecting the front-end to the back-end.
You
said:
WRITE 10 ASSIGNMENTS FROM ABOVE CONCEPT WITH STEP BY STEP SOLUTIONS with
proper explanation in details
ChatGPT
said:
Assignments for Class 30: Building a Complete
Node.js Application
These assignments will help reinforce your
understanding of building a complete Node.js application. Each assignment will
focus on different aspects of the project and guide you through the process of
building a To-Do app with CRUD operations, authentication, and API routes.
Assignment 1: Setting Up a Node.js Project
Task: Initialize a new
Node.js project and install necessary dependencies.
Step-by-Step Solution:
1. Create a
new directory for your project:
bashmkdir todo-appcd todo-app
2. Initialize
the project:
bashnpm init -y
This will generate a package.json file with
default values.
3. Install
dependencies: Install the required dependencies (Express,
Mongoose, bcryptjs, jsonwebtoken, body-parser, dotenv):
bashnpm install express mongoose bcryptjs jsonwebtoken body-parser dotenv
4. Create a
basic server file (server.js)
to set up the Express server and test the connection:
jsconst express = require('express');const mongoose = require('mongoose');require('dotenv').config(); const app = express();app.use(express.json()); mongoose.connect(process.env.DB_URI, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log("Connected to MongoDB")) .catch((err) => console.log("Database connection error", err)); const PORT = process.env.PORT || 3000;app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
5. Create a
.env file to
store your database URI:
bashDB_URI=mongodb://localhost:27017/todo-app
Assignment 2: Creating a User Model
Task: Create a User model to store user
information, including email, password, and username.
Step-by-Step Solution:
1. Create a
new folder named models
and inside it, create a file User.js.
2. Define
the schema for the User
model:
jsconst mongoose = require('mongoose');const bcrypt = require('bcryptjs'); const userSchema = new mongoose.Schema({ username: { type: String, required: true }, email: { type: String, required: true, unique: true }, password: { type: String, required: true },}); // Pre-save hook for hashing passwordsuserSchema.pre('save', async function(next) { if (!this.isModified('password')) return next(); const salt = await bcrypt.genSalt(10); this.password = await bcrypt.hash(this.password, salt); next();}); const User = mongoose.model('User', userSchema);module.exports = User;
3. Explanation:
This model defines the schema for user registration with email, username, and
password fields. The password is hashed before being saved using the bcryptjs library.
Assignment 3: User Registration Endpoint
Task: Implement a route
for user registration that accepts username,
email, and password, hashes the
password, and saves the user to the database.
Step-by-Step Solution:
1. In
your server.js
file, import the User model and define the registration
route:
jsconst User = require('./models/User');const jwt = require('jsonwebtoken'); app.post('/register', async (req, res) => { const { username, email, password } = req.body; try { const user = new User({ username, email, password }); await user.save(); const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, { expiresIn: '1h' }); res.status(201).json({ token }); } catch (err) { res.status(400).json({ message: 'Error registering user' }); }});
2. Explanation:
This route allows a new user to register. Upon successful registration, a JWT
token is generated and sent back to the user for authentication purposes.
Assignment 4: User Login Endpoint
Task: Implement a route
for user login that verifies the email and password, and returns a JWT token.
Step-by-Step Solution:
1. In server.js, add the login
route:
jsapp.post('/login', async (req, res) => { const { email, password } = req.body; const user = await User.findOne({ email }); if (!user) return res.status(400).json({ message: 'Invalid credentials' }); const isMatch = await bcrypt.compare(password, user.password); if (!isMatch) return res.status(400).json({ message: 'Invalid credentials' }); const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, { expiresIn: '1h' }); res.status(200).json({ token });});
2. Explanation:
The login route checks if the email exists in the database and compares the
provided password with the stored hashed password. If successful, a JWT token
is returned.
Assignment 5: Creating a Task Model
Task: Create a Task model that includes
fields for the task title, description, completion status, and the user who
created it.
Step-by-Step Solution:
1. Create
a file Task.js
inside the models
folder and define the schema:
jsconst mongoose = require('mongoose'); const taskSchema = new mongoose.Schema({ title: { type: String, required: true }, description: String, completed: { type: Boolean, default: false }, user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },}); const Task = mongoose.model('Task', taskSchema);module.exports = Task;
2. Explanation:
This model defines the schema for a task, with fields for the title,
description, completion status, and the user who created the task (referencing
the User
model).
Assignment 6: Creating a Task (POST) Endpoint
Task: Implement a route
for creating a task, ensuring that the task is associated with the logged-in
user.
Step-by-Step Solution:
1. In server.js, create the POST /tasks route:
jsconst authenticate = require('./middleware/authenticate'); // Import authentication middlewareconst Task = require('./models/Task'); app.post('/tasks', authenticate, async (req, res) => { const { title, description } = req.body; const userId = req.user.userId; // From authentication middleware try { const task = new Task({ title, description, user: userId }); await task.save(); res.status(201).json(task); } catch (err) { res.status(400).json({ message: 'Error creating task' }); }});
2. Explanation:
This route allows users to create tasks. The authenticate
middleware ensures that only logged-in users can create tasks.
Assignment 7: Fetching Tasks (GET) Endpoint
Task: Implement a route
to fetch all tasks for the logged-in user.
Step-by-Step Solution:
1. In server.js, create the GET /tasks route:
jsapp.get('/tasks', authenticate, async (req, res) => { const userId = req.user.userId; try { const tasks = await Task.find({ user: userId }); res.status(200).json(tasks); } catch (err) { res.status(500).json({ message: 'Error fetching tasks' }); }});
2. Explanation:
This route fetches all tasks that belong to the logged-in user by querying the Task collection using the user field.
Assignment 8: Updating a Task (PUT) Endpoint
Task: Implement a route
to update an existing task, including the ability to mark a task as completed
or update its title and description.
Step-by-Step Solution:
1. In server.js, create the PUT /tasks/:id route:
jsapp.put('/tasks/:id', authenticate, async (req, res) => { const { title, description, completed } = req.body; try { const task = await Task.findByIdAndUpdate(req.params.id, { title, description, completed }, { new: true }); if (!task) return res.status(404).json({ message: 'Task not found' }); res.status(200).json(task); } catch (err) { res.status(400).json({ message: 'Error updating task' }); }});
2. Explanation:
This route allows users to update the task's title, description, or completion
status. The task is identified by its id
in the request URL.
Assignment 9: Deleting a Task (DELETE)
Endpoint
Task: Implement a route
to delete an existing task by its id.
Step-by-Step Solution:
1. In server.js, create the DELETE /tasks/:id route:
jsapp.delete('/tasks/:id', authenticate, async (req, res) => { try { const task = await Task.findByIdAndDelete(req.params.id); if (!task) return res.status(404).json({ message: 'Task not found' }); res.status(200).json({ message: 'Task deleted' }); } catch (err) { res.status(400).json({ message: 'Error deleting task' }); }});
2. Explanation:
This route allows users to delete a task by its id.
Assignment 10: Authentication Middleware
Task: Create a middleware
function to authenticate the user by verifying the JWT token.
Step-by-Step Solution:
1. Create
a new file middleware/authenticate.js:
jsconst jwt = require('jsonwebtoken'); const authenticate = (req, res, next) => { const token = req.header('x-auth-token'); if (!token) return res.status(401).json({ message: 'No token, authorization denied' }); try { const decoded = jwt.verify(token, process.env.JWT_SECRET); req.user = decoded; next(); } catch (err) { res.status(401).json({ message: 'Token is not valid' }); }}; module.exports = authenticate;
2. Explanation:
This middleware checks if the JWT token is provided in the request header and
verifies it using the jsonwebtoken
library. If valid, it adds the user's information to the request object and
proceeds to the next middleware or route handler.
These assignments cover the core aspects of
building a complete Node.js application with user authentication and CRUD
operations for tasks. By completing these, you will gain hands-on experience in
working with Express, MongoDB, JWT, and middleware for authentication.
You
said:
WRITE 50 no of MCQs only FROM ABOVE CONCEPT with explanation
ChatGPT
said:
Here are 50
multiple-choice questions (MCQs) based on the concept of
building a complete Node.js application as explained in the previous lessons,
with detailed explanations for each answer.
1. Which of the following is the first step
in setting up a Node.js project?
a) Install Node.js
b) Initialize a new project with npm
init
c) Install Express.js
d) Create the server.js
file
Answer: b)
Initialize a new project with npm
init
Explanation: The first step in setting up a Node.js
project is initializing it using npm
init, which generates a package.json
file that manages dependencies and configurations for the project.
2. Which package is used to handle HTTP
requests and routing in a Node.js project?
a) Mongoose
b) Express
c) bcryptjs
d) jsonwebtoken
Answer: b)
Express
Explanation: Express is a web framework for Node.js
that simplifies routing, middleware handling, and HTTP requests.
3. Which command is used to install
dependencies in a Node.js project?
a) npm start
b) npm install
c) npm init
d) npm run
Answer: b)
npm install
Explanation: The npm
install command installs all dependencies listed in the package.json file.
4. What does the mongoose.connect()
function do in a Node.js application?
a) Starts the Express server
b) Establishes a connection to a MongoDB database
c) Configures environment variables
d) Creates a new MongoDB database
Answer: b)
Establishes a connection to a MongoDB database
Explanation: The mongoose.connect()
function connects your Node.js application to a MongoDB database.
5. Which of the following is used to securely
store database credentials in a Node.js application?
a) Hardcode credentials in the code
b) Use environment variables with the dotenv
package
c) Use config.json
file
d) Store them in a database
Answer: b)
Use environment variables with the dotenv
package
Explanation: Storing sensitive credentials, like
database URIs, in environment variables using the dotenv
package helps protect them from exposure.
6. Which function is used to hash passwords
before saving them in the database?
a) bcrypt.hash()
b) bcrypt.compare()
c) bcrypt.genSalt()
d) bcrypt.hashSync()
Answer: a)
bcrypt.hash()
Explanation: bcrypt.hash()
is used to hash passwords before storing them in the database for security.
7. What is the purpose of JWT (JSON Web
Token) in Node.js applications?
a) To encrypt the database
b) To securely store the password
c) To authenticate users by generating a token
d) To make the application run faster
Answer: c)
To authenticate users by generating a token
Explanation: JWT is used to securely transmit user
authentication data between the client and server, often after a successful
login.
8. What is the purpose of app.use(express.json()) in an
Express app?
a) To parse incoming JSON data into
JavaScript objects
b) To handle static files
c) To parse query parameters
d) To log incoming requests
Answer: a)
To parse incoming JSON data into JavaScript objects
Explanation: express.json()
is a built-in middleware that parses incoming requests with JSON payloads.
9. Which HTTP method is used to fetch all
tasks from the server?
a) POST
b) GET
c) PUT
d) DELETE
Answer: b)
GET
Explanation: The GET method is used to retrieve data
from the server, such as fetching a list of tasks.
10. What does the req.body object
contain in an Express route handler?
a) Request headers
b) Request URL
c) The body of the HTTP request
d) The session data
Answer: c)
The body of the HTTP request
Explanation: The req.body
object contains data sent in the body of a POST or PUT request, such as form
data or JSON data.
11. Which MongoDB function is used to save a
new document in the database?
a) insert()
b) save()
c) store()
d) create()
Answer: b) save()
Explanation: The save()
function is used to insert a new document into the collection or update an
existing one if it already exists.
12. In a Node.js application, which method is
used to authenticate users?
a) auth.authenticate()
b) passport.authenticate()
c) jwt.verify()
d) jsonwebtoken.verify()
Answer: d) jsonwebtoken.verify()
Explanation: jsonwebtoken.verify()
is used to authenticate users by verifying the validity of the JWT token.
13. Which middleware function is responsible
for checking if a JWT token is valid?
a) authenticate()
b) authToken()
c) validateToken()
d) jwtVerify()
Answer: a) authenticate()
Explanation: authenticate()
middleware verifies the JWT token provided by the client to ensure that the
user is authenticated.
14. Which of the following is NOT a typical
field in a MongoDB user schema?
a) username
b) password
c) email
d) passwordConfirmation
Answer: d) passwordConfirmation
Explanation: passwordConfirmation
is not typically stored in the database. It is used only in the registration
process to verify that the user entered the same password twice.
15. Which method is used to hash passwords in
Node.js using bcrypt?
a) bcrypt.compare()
b) bcrypt.hashSync()
c) bcrypt.genSaltSync()
d) bcrypt.hash()
Answer: b) bcrypt.hashSync()
Explanation: bcrypt.hashSync()
is a synchronous method to hash passwords using bcrypt.
16. What is the correct way to handle
authentication errors in Express routes?
a) Throw an error
b) Send a response with a 400 or 401 status code
c) Redirect to a login page
d) Close the connection
Answer: b)
Send a response with a 400 or 401 status code
Explanation: In case of authentication errors, it is
standard practice to send a 400 or 401 HTTP status code along with an error
message.
17. What is a correct way to fetch tasks for
a specific user from the database?
a) Task.findById()
b) Task.find()
c) Task.findOne()
d) Task.find({ userId:
'userId' })
Answer: d) Task.find({ userId: 'userId' })
Explanation: To fetch tasks for a specific user, use
Task.find()
and filter by userId.
18. What is the purpose of mongoose.Schema.Types.ObjectId?
a) It is used for defining text fields in
MongoDB
b) It is used to store the ID of a referenced document
c) It is used to create primary keys
d) It is used to store numbers
Answer: b)
It is used to store the ID of a referenced document
Explanation: mongoose.Schema.Types.ObjectId
is used to store references to other documents, such as the ID of a user for a
task.
19. Which method in MongoDB is used to delete
a document by its ID?
a) delete()
b) deleteOne()
c) remove()
d) findByIdAndDelete()
Answer: d) findByIdAndDelete()
Explanation: findByIdAndDelete()
is used to find a document by its ID and delete it from the database.
20. What is the role of the jsonwebtoken.sign() method?
a) To encrypt user data
b) To generate a JWT token
c) To verify the token’s authenticity
d) To send a response
Answer: b)
To generate a JWT token
Explanation: jsonwebtoken.sign()
is used to generate a JWT token containing the user's data.
21. What does the res.json() method
do in Express?
a) Sends HTML content to the client
b) Sends a JSON response to the client
c) Logs the response data
d) Encrypts the response data
Answer: b)
Sends a JSON response to the client
Explanation: res.json()
is used to send a JSON-formatted response to the client.
22. Which Express method is used to handle
POST requests?
a) app.post()
b) app.get()
c) app.put()
d) app.delete()
Answer: a) app.post()
Explanation: app.post()
is used to handle POST requests, typically used for creating new resources.
23. Which HTTP status code indicates that a
request was successful?
a) 200
b) 301
c) 400
d) 500
Answer: a)
200
Explanation: A 200 status code indicates that the
request was successful.
24. How do you protect sensitive data like
passwords in a Node.js application?
a) Use encryption for all data
b) Use hashing algorithms like bcrypt
c) Store them in an encrypted database
d) Store them in environment variables
Answer: b)
Use hashing algorithms like bcrypt
Explanation: Hashing algorithms like bcrypt ensure
that passwords are stored securely in the database.
25. Which of the following is the correct way
to check if a user is authenticated in a route handler?
a) if
(req.user) { ... }
b) if (req.session.user) {
... }
c) if
(req.isAuthenticated()) { ... }
d) All of the above
Answer: d)
All of the above
Explanation: All of these methods can be used to
check if a user is authenticated, depending on the authentication strategy
used.
26. Which method is used to update a document
in MongoDB?
a) update()
b) updateOne()
c) save()
d) findOneAndUpdate()
Answer: d) findOneAndUpdate()
Explanation: findOneAndUpdate()
is used to find a document by a query and update it.
27. How can we use middleware to handle
errors in Express?
a) Using next(err)
to pass errors to the error handler
b) By throwing errors directly in the route handler
c) By using res.status()
method
d) All of the above
Answer: a)
Using next(err) to
pass errors to the error handler
Explanation: In Express, next(err) is used to pass
errors to an error-handling middleware function.
28. What is the default method used by forms
in HTML for submitting data?
a) PUT
b) POST
c) GET
d) DELETE
Answer: b)
POST
Explanation: By default, forms use the POST method
to submit data to the server.
29. Which Node.js module is used to handle
file system operations?
a) fs
b) path
c) express
d) http
Answer: a)
fs
Explanation: The fs
module is used to handle file system operations, like reading and writing
files.
30. What is the primary purpose of the res.status() method?
a) To send the status code with the response
b) To log the status code
c) To process the request
d) To redirect the user
Answer: a)
To send the status code with the response
Explanation: The res.status()
method is used to set the HTTP status code for the response.
31. What is app.listen() used
for in an Express application?
a) To initialize the app
b) To start the server
c) To define routes
d) To handle incoming requests
Answer: b)
To start the server
Explanation: app.listen()
is used to start the server and specify the port on which the app will listen
for incoming requests.
32. How can you validate user input in a
Node.js application?
a) Using regular expressions
b) Using a validation library like Joi
c) Manually checking the data in route handlers
d) All of the above
Answer: d)
All of the above
Explanation: Input validation can be done using
regular expressions, libraries like Joi, or manual checks within route
handlers.
33. What is the mongoose.Schema() used
for in MongoDB?
a) To create a new document
b) To define the structure of documents in a collection
c) To store queries
d) To update documents in a collection
Answer: b)
To define the structure of documents in a collection
Explanation: mongoose.Schema()
is used to define the structure and types of data for a document.
34. What is an API route in a Node.js
application used for?
a) To define database queries
b) To handle HTTP requests from the client
c) To manage middleware
d) To start the server
Answer: b)
To handle HTTP requests from the client
Explanation: API routes are used to handle HTTP
requests such as GET, POST, PUT, DELETE, and interact with the database or
other services.
35. Which of the following is used to encrypt
sensitive user data, like passwords?
a) hash()
b) crypt()
c) bcrypt()
d) secure()
Answer: c) bcrypt()
Explanation: bcrypt()
is a popular encryption algorithm used to hash passwords before storing them in
a database.
36. What does res.send() do in
an Express route?
a) Sends a response with status code
b) Sends a plain text response
c) Sends JSON-formatted response
d) Both b and c
Answer: d)
Both b and c
Explanation: res.send()
can send both plain text and JSON data as a response to the client.
37. How would you retrieve query parameters
in a Node.js application using Express?
a) req.query
b) req.body
c) req.params
d) req.headers
Answer: a) req.query
Explanation: Query parameters can be accessed using req.query, which contains
the parsed query string parameters from the URL.
38. Which function is used to start a Node.js
HTTP server?
a) http.start()
b) app.listen()
c) server.listen()
d) app.start()
Answer: b) app.listen()
Explanation: app.listen()
is used to start the HTTP server and listen for requests on the specified port.
39. What does app.use() do in
Express?
a) Handles routing
b) Sets middleware for HTTP requests
c) Starts the server
d) Creates a new route
Answer: b)
Sets middleware for HTTP requests
Explanation: app.use()
is used to add middleware to the application for processing requests and
responses.
40. What is the role of the express.Router() in an
Express app?
a) To handle HTTP requests
b) To define API routes and modularize code
c) To parse incoming data
d) To set headers
Answer: b)
To define API routes and modularize code
Explanation: express.Router()
is used to define and modularize different sets of routes in an Express
application.
41. What does the res.redirect()
function do in Express?
a) Redirects the request to another URL
b) Sends a response with status code
c) Updates the user session
d) Sends a JSON response
Answer: a)
Redirects the request to another URL
Explanation: res.redirect()
is used to send a redirect response, directing the client to a different URL.
42. What is the role of app.use(express.static()) in
Express?
a) To serve static files like images, CSS,
and JavaScript
b) To parse incoming data
c) To start the server
d) To handle routes
Answer: a)
To serve static files like images, CSS, and JavaScript
Explanation: app.use(express.static())
is used to serve static files from a directory to the client.
43. Which of the following is used to manage
user sessions in Node.js?
a) express-session
b) jsonwebtoken
c) passport
d) cookie-parser
Answer: a) express-session
Explanation: express-session
is a middleware used for managing user sessions in Express-based applications.
44. What is the default port number for a
Node.js server?
a) 5000
b) 8080
c) 3000
d) 4000
Answer: c)
3000
Explanation: By convention, Node.js servers often
run on port 3000 unless specified otherwise.
45. What does next() do in
middleware functions?
a) It terminates the request-response cycle
b) It forwards the request to the next middleware function
c) It sends the response to the client
d) It logs the request data
Answer: b)
It forwards the request to the next middleware function
Explanation: next()
is used to pass the control to the next middleware function in the
request-response cycle.
46. Which of the following is used to parse
incoming query string parameters?
a) express.json()
b) express.urlencoded()
c) express.query()
d) express.raw()
Answer: b) express.urlencoded()
Explanation: express.urlencoded()
is used to parse incoming requests with URL-encoded data.
47. How can you handle both POST and GET
requests in Express?
a) Use different routes for each method
b) Use app.all()
c) Use app.handle()
d) Use app.use()
Answer: a)
Use different routes for each method
Explanation: POST and GET requests are typically
handled separately with app.post()
and app.get()
respectively.
48. What does the app.set()
function do in Express?
a) Defines a middleware
b) Sets global variables or configurations
c) Starts the server
d) Handles a route
Answer: b)
Sets global variables or configurations
Explanation: app.set()
is used to set configurations like the view engine or port number in an Express
application.
49. What is req.params used
for in Express?
a) To get the data sent in the body of the
request
b) To get the query string data from the URL
c) To get route parameters from the URL
d) To get headers from the request
Answer: c)
To get route parameters from the URL
Explanation: req.params
contains the route parameters extracted from the URL.
50. How do you make a GET request to an API
in Node.js?
a) Using axios.get()
b) Using http.request()
c) Using request.get()
d) All of the above
Answer: d)
All of the above
Explanation: All of these methods can be used to
make a GET request to an API in Node.js.

No comments:
Post a Comment