Introduction
We check the data sent by users to make sure it is correct and safe before using it.
Jump into concepts and practice - no test required
We check the data sent by users to make sure it is correct and safe before using it.
app.post('/route', (req, res) => { const { field } = req.body; if (!field) { return res.status(400).send('Field is required'); } // continue processing });
req.body to access data sent in the request body.app.post('/signup', (req, res) => { const { email } = req.body; if (!email) { return res.status(400).send('Email is required'); } res.send('Signup successful'); });
app.post('/login', (req, res) => { const { username, password } = req.body; if (!username || !password) { return res.status(400).send('Username and password are required'); } res.send('Login successful'); });
app.post('/order', (req, res) => { const { quantity } = req.body; if (typeof quantity !== 'number' || quantity <= 0) { return res.status(400).send('Quantity must be a positive number'); } res.send('Order placed'); });
This Express app listens for POST requests to /register. It checks if the username and password are sent and if the password is long enough. If any check fails, it sends an error message. Otherwise, it confirms registration.
import express from 'express'; const app = express(); app.use(express.json()); app.post('/register', (req, res) => { const { username, password } = req.body; if (!username) { return res.status(400).send('Username is required'); } if (!password) { return res.status(400).send('Password is required'); } if (password.length < 6) { return res.status(400).send('Password must be at least 6 characters'); } res.send(`User ${username} registered successfully`); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Always use express.json() middleware to parse JSON body data.
Validation helps keep your app safe and working well.
For complex validation, consider libraries like Joi or express-validator.
Check user data in req.body before using it.
Send clear error messages if data is missing or wrong.
Use middleware to parse JSON body data.
req.body in an Express app?req.body.name is missing?
app.post('/user', (req, res) => {
if (!req.body.name) {
return res.status(400).send('Name is required');
}
res.send(`Hello, ${req.body.name}`);
});app.post('/login', (req, res) => {
if (req.body.username === undefined || req.body.password === undefined) {
res.status(400).send('Missing fields');
}
res.send('Login success');
});req.body.age is a number greater than 18 before processing. Which code snippet correctly validates this and sends a 400 error if invalid?