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 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"}'
-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"
}
}
"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
Post a Comment