Here are code snippets illustrating some common mistakes in Express.js along with their solutions:
1. Improper Error Handling:
Mistake:
app.get('/users', (req, res) => {
// Logic to fetch users
// If an error occurs:
res.status(500).send('Internal Server Error');
});
Solution:
app.get('/users', (req, res, next) => {
// Logic to fetch users
// If an error occurs:
next(new Error('Unable to fetch users'));
});
// Error handling middleware
app.use((err, req, res, next) => {
res.status(500).send({ error: err.message });
});
2. Neglecting Security Measures:
Mistake:
// Handling a POST request without data validation
app.post('/login', (req, res) => {
const username = req.body.username;
const password = req.body.password;
// Perform login without validating input
});
Solution:
const { body, validationResult } = require('express-validator');
// Data validation middleware
app.post('/login', [
body('username').isLength({ min: 5 }),
body('password').isLength({ min: 8 }),
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// Perform login after validating input
});
3. Using Synchronous Operations:
Mistake:
app.get('/data', (req, res) => {
const result = fetchData(); // Synchronous operation
res.json(result);
});
Solution:
app.get('/data', async (req, res) => {
try {
const result = await fetchData(); // Asynchronous operation
res.json(result);
} catch (error) {
res.status(500).send('Error fetching data');
}
});
These examples demonstrate how to handle errors, implement data validation, and use asynchronous operations properly within Express.js to avoid common mistakes and ensure better code quality and security.
Top comments (0)