NodeJS DAY 5
NodeJS DAY 5
{
"name": "Alice",
"age": 28,
"work":" chef",
"mobile": "123-456-7890",
"email":" [email protected]",
"address": "123 Main St, City",
"salary":60000
}
Parameters
Type, requires, unique, etc.
WHAT IS body-parser
Body Parser is a middleware library for Express.js
It is used to parser & extract the body of incoming HTTP requests.
When a client (e.g., a web browser or a mobile app) sends data to a
server, it typically includes that data in the body of an HTTP request.
This data can be in various formats, such as JSON, form, data, or URL-
encoded data. Body Parser helps parse & extract this data form the
request! So that you can work with it in your Express.js application.
Body Parser processes the request body before it reaches your route
handlers, making the parsed data available in the req. body for further
processing.
bodyParser.json() automatically parser the JSON data from the request
body and converts it into a JavaScript object, which is then stored in the
req. body
We need an Endpoint where the client sends data and data needs to be
saved in the database
newPerson.save((error, savedPerson)=>{
if(error){
console.error('Error is saving person: ',error);
res.status(500).json({error: 'internal server error'});
}else{
console.log('Data saved');
res.status(201).json(savedPerson);
}
});
try{
const data = req.body //Assuming the request body contain the
person data
Await (await):
The await keyword is used inside an async function to wait for the
resolution of a promise. It can only be used within an async function.
When await is used, the function pauses at that line until the promise is
resolved or rejected. This allows you to write code that appears
sequential, even though it’s performing asynchronous tasks.
If the promise is resolved, the result of the promise is returned. If the
promise is rejected, it throws an error that can be caught using try…
catch.
CRUD application