This Express server listens for POST requests to /register. It checks the request body against the userSchema. If the data is wrong, it sends back an error message. If correct, it confirms the data is valid.
import express from 'express';
import Joi from 'joi';
const app = express();
app.use(express.json());
const userSchema = Joi.object({
username: Joi.string().alphanum().min(3).max(30).required(),
email: Joi.string().email().required(),
age: Joi.number().integer().min(0).optional()
});
app.post('/register', (req, res) => {
const { error, value } = userSchema.validate(req.body);
if (error) {
return res.status(400).json({ error: error.details[0].message });
}
res.json({ message: 'User data is valid', data: value });
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});