0% found this document useful (0 votes)
8 views

13 Practical

Uploaded by

nikhil patil
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)
8 views

13 Practical

Uploaded by

nikhil patil
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/ 2

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', [
// Validate and sanitize fields
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!'
}); // Send a generic error response
});

// Start the server


app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Output-valid input
curl -X POST "http://localhost:3000/submit" -H "Content-Type: application/json" -d
"{\"username\": \"john_doe\", \"email\": \"[email protected]\"}"
JSON Output
{
"success": true,
"message": "Data received successfully!",
"data": {
"username": "john_doe",
"email": "[email protected]"
}
}

Output- Invalid
curl -X POST "http://localhost:3000/submit" -H "Content-Type: application/json" -d
"{\"username\": \"\", \"email\": \"invalid-email\"}"
{
"success": false,
"errors": [
{
"msg": "Username is required",
"param": "username",
"location": "body"
},
{
"msg": "Must be a valid email address",
"param": "email",
"location": "body"
}
]
}

You might also like