const express = require('express');
const { body, sanitizeBody, validationResult } = require('express-validator');
const app = express();
app.use(express.json());
// Define a route handler that uses request validation middleware
app.post('/register',
body('username').trim().isLength({ min: 3, max: 30 })
.withMessage('Username must be between 3 and 30 characters long')
.escape(),
body('email').trim().isEmail()
.withMessage('Please enter a valid email address')
.normalizeEmail(),
body('password').isLength({ min: 6 })
.withMessage('Password must be at least 6 characters long')
.matches(/\d/)
.withMessage('Password must contain at least one number')
.customSanitizer((value, { req }) => {
// Hash the password before storing it in the database
const hashedPassword = hashPassword(value);
req.body.password = hashedPassword;
return hashedPassword;
}),
(req, res) => {
// Check for validation errors
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
// Sanitize input data
sanitizeBody('username').escape();
sanitizeBody('email').normalizeEmail();
// Registration logic here
const username = req.body.username;
const email = req.body.email;
const password = req.body.password;
const message = `Registered user: ${username} (${email}, ${password})`;
res.send(message);
});
// Start the server
app.listen(3000, () => {
console.log('Server running on port 3000');
});