0% found this document useful (0 votes)
46 views6 pages

Mern Exp-11

The document discusses various concepts related to APIs and web application development: - Postman is a tool for testing APIs that allows sending HTTP requests and automating tests. - In Express.js, middleware sits between requests and responses to perform tasks like authentication and logging. - The req and res objects represent the incoming request and outgoing response in route handling. - app.get() handles GET requests while app.post() handles POST requests for retrieving or sending data. - A MongoDB driver connects to MongoDB while an ODM maps objects to documents for a simplified interface.

Uploaded by

Preethi Sri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views6 pages

Mern Exp-11

The document discusses various concepts related to APIs and web application development: - Postman is a tool for testing APIs that allows sending HTTP requests and automating tests. - In Express.js, middleware sits between requests and responses to perform tasks like authentication and logging. - The req and res objects represent the incoming request and outgoing response in route handling. - app.get() handles GET requests while app.post() handles POST requests for retrieving or sending data. - A MongoDB driver connects to MongoDB while an ODM maps objects to documents for a simplified interface.

Uploaded by

Preethi Sri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

MSWD EXP-11

PRELAB:

1. Explain in brief about Postman?


Postman is a popular software tool for testing and working with APIs. It simplifies API
testing, automation, and documentation, allowing developers to send HTTP requests,
automate tests, manage variables, and create API documentation, among other features.
It's a crucial tool for anyone involved in API development and testing.

2. What is Middleware in Express JS?

In Express.js, middleware are functions that handle HTTP requests and responses.
They sit between the server receiving a request and the server sending a response, allowing you
to perform tasks like authentication, data parsing, and logging. Middleware functions can be
used to process or modify the request or response, making them a powerful tool for building
web applications.

3. What is the purpose of the req and res objects in route handling?

In route handling with web frameworks like Express.js, the `req` (request) object
represents the incoming HTTP request from the client, containing information about the
request, such as parameters, headers, and data sent by the client. The `res` (response) object is
used to craft and send the HTTP response back to the client, including setting headers, status
codes, and sending data. These objects are essential for handling and responding to client
requests in web applications.

4. Explain the difference between app.get() and app.post() in route handling.

In route handling with Express.js:

- `app.get()` is used to define routes that handle HTTP GET requests. It's typically used for
retrieving data from the server without causing any changes to the server or data.

- `app.post()` is used to define routes that handle HTTP POST requests. It's often used for
submitting data to the server, which can then be processed, stored, or modified.

The key difference is in the type of HTTP request they handle: `app.get()` is for reading data,
while `app.post()` is for sending and processing data.

5. What is MongoDB driver or an Object Document Mapper (ODM).

A MongoDB driver is a software component or library that enables applications to


interact with a MongoDB database. It provides a way to connect to the database, send queries,
and retrieve data.

An Object Document Mapper (ODM), on the other hand, is a higher-level tool used in object-
oriented programming to interact with MongoDB. It maps objects in your application code to
documents in the MongoDB database, providing a more abstract and simplified way to work
with MongoDB, similar to how an ORM (Object-Relational Mapping) works with relational
databases.
In short, a MongoDB driver is a lower-level interface to communicate with MongoDB, while
an ODM is a higher-level tool that helps developers work with MongoDB in a more object-
oriented way.

IN LAB: -

Exercise 1: Create a simple server with nodeJs and import Express framework to create
endpoints.
a. Define a GET route for the homepage which sends “Hellow World” response.
b. The app should listen on a specific port no-3001
Exercise 2: Use mongoose module to create a schema for Users Collection in MongoDB
Local Database. Create a connection URL and database name for local database. Define a
POST route for creating a new user.

Post-Lab:
Question 1: Define a PUT route for updating a user. Define a DELETE route for deleting a
user.

To define PUT and DELETE routes for updating and deleting a user in an
Express.js application, you can use the following code as an example:

```javascript
const express = require('express');
const app = express();
const bodyParser = require('body-parser');

app.use(bodyParser.json());

// Sample in-memory user data


let users = [
{ id: 1, name: 'User1' },
{ id: 2, name: 'User2' },
{ id: 3, name: 'User3' }
];

// PUT route for updating a user


app.put('/users/:id', (req, res) => {
const userId = parseInt(req.params.id);
const updatedUser = req.body;

// Find the user by ID and update their data


const userIndex = users.findIndex(user => user.id === userId);

if (userIndex !== -1) {


users[userIndex] = { id: userId, ...updatedUser };
res.json({ message: 'User updated successfully', user: users[userIndex] });
} else {
res.status(404).json({ message: 'User not found' });
}
});

// DELETE route for deleting a user


app.delete('/users/:id', (req, res) => {
const userId = parseInt(req.params.id);

// Find the user by ID and remove them


const userIndex = users.findIndex(user => user.id === userId);

if (userIndex !== -1) {


users.splice(userIndex, 1);
res.json({ message: 'User deleted successfully' });
} else {
res.status(404).json({ message: 'User not found' });
}
});

app.listen(3000, () => {
console.log('Server is running on port 3000');
});
```

- The `PUT` route allows you to update a user's information by specifying their ID in the URL
and providing the updated data in the request body.
- The `DELETE` route allows you to delete a user by specifying their ID in the URL.

Please note that this is a basic example, and in a real-world application, you would typically
interact with a database to update and delete user records.

Question 2: Define a async function that can handle errors occurred from CRUD
operations using try-catch methods.
To define an asynchronous function that can handle errors that occur during CRUD
(Create, Read, Update, Delete) operations using try-catch, you can create an example
function like this:

```javascript

// Example asynchronous function for CRUD operations with error handling

async function performCRUDOperation() {

try {

// Simulate a CRUD operation that may throw an error

// Replace this with your actual CRUD logic

const result = await performActualCRUDOperation();

// If the CRUD operation was successful, return the result

return result;

} catch (error) {

// Handle the error

console.error('Error occurred during CRUD operation:', error);

// You can choose to rethrow the error for further handling or return an error
response

// throw error;

return { error: 'CRUD operation failed' };

async function performActualCRUDOperation() {

return 'CRUD operation successful';

performCRUDOperation()
.then(result => {

if (result.error) {

console.log('Error Response:', result.error);

} else {

console.log('Success Response:', result);

})

.catch(err => {

console.error('Unhandled Error:', err);

});

```

- The `performCRUDOperation` function is an asynchronous function that wraps the


actual CRUD operation.

- Inside the `try` block, it calls the `performActualCRUDOperation` function, which


simulates a CRUD operation and may throw an error.

- If an error occurs, it's caught in the `catch` block, where you can handle the error.
You can choose to rethrow the error for further handling or return an error response.

This structure allows you to handle errors gracefully and provide appropriate
responses in your CRUD operations. Remember to replace the
`performActualCRUDOperation` function with your actual database or data-related
operations.

You might also like