FSD-II Practical Assignment-13(Slip13_expressJS)

 13.Extend the previous Express.js application to include middleware for parsing request bodies (e.g., JSON, form data) and validating input data. Send appropriate JSON responses for success and error cases.




const express = require('express');
const { body, validationResult } = require('express-validator');

const app = express();
const port = 3000;

// Middleware to parse JSON bodies
app.use(express.json());

// Middleware to parse URL-encoded bodies
app.use(express.urlencoded({ extended: true }));

// Example route with input validation
app.post(
'/submit',
[
body('username')
.isString()
.trim()
.notEmpty()
.withMessage('Username is required'),
body('email')
.isEmail()
.withMessage('Must be a valid email address'),
],
(req, res) => {
// Check for validation errors
const errors = validationResult(req);

if (!errors.isEmpty()) {
return res.status(400).json({
success: false,
errors: errors.array(),
});
}

// Process the valid data
const { username, email } = req.body;

res.status(200).json({
success: true,
message: 'Data received successfully!',
data: { username, email },
});
}
);

// Error Handling Middleware
app.use((err, req, res, next) => {
console.error(err.stack); // Log the error stack for debugging
res.status(500).json({
success: false,
message: 'Something went wrong!',
});
});

// Start the server
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});

output-
1)Run the server- open terminal
    node server.js
2)Test the /submit endpoint- open another terminal
curl -X POST http://localhost:3000/submit \
-H "Content-Type: application/json" \
-d '{"username":"testuser","email":"test@example.com"}'
 
Expected output (success):
{
"success": true,
"message": "Data received successfully!",
"data": {
"username": "testuser",
"email": "test@example.com"
}
}

4)If you miss a field:

curl -X POST http://localhost:3000/submit \
-H "Content-Type: application/json" \
-d '{"username":""}'
Output:

{
"success": false,
"errors": [
{ "type": "field", "msg": "Username is required", "path": "username", "location": "body" },
{ "type": "field", "msg": "Must be a valid email address", "path": "email", "location": "body" }
]
}
 



 

Comments

Popular posts from this blog

Slip 11: Write node js application that transfer a file as an attachment on web and enables browser to prompt the user to download file using express js.

Slip 7 Create a node js file named main.js for event-driven application. There should be a main loop that listens for events, and then triggers a callback function when one of those events is detected.

Slip 1(a) Write an Angular 13 application addition of two numbers using ng-init, ng-model & ng-bind. And also demonstrate ng-show, ng-disabled, ng-click directives on button component.