What are Controllers?
- Controllers are functions that handle the logic for processing incoming HTTP requests and sending appropriate responses.
- They separate business logic from route definitions, keeping your code organized and clean.
- Typically, each controller corresponds to a resource or feature (like
userController
, productController
, etc.)
Example Controller
// controllers/userController.js
exports.getAllUsers = (req, res) => {
res.send("List of all users");
};
exports.createUser = (req, res) => {
const newUser = req.body;
res.send(`User created: ${newUser.name}`);
};
exports
makes these controller functions available to other files (like route files).
Why Use Controllers?
- Keeps routing clean and readable
- Promotes modularity and reusability
- Separates concerns (routes → controller → service → database)