Working with controllers in Express.js
In the previous parts of this tutorial, we have learned how to set up a basic web app using Express.js and how to handle routing. In this part, we will focus on working with controllers to handle the logic of our application.
Controllers are responsible for handling the requests from the client and returning the appropriate response. They help to keep the routes clean and structured by separating the logic from the route definitions.
Creating a controller
To create a controller in Express.js, you can simply create a new file for each controller and define the logic for handling a specific set of routes. For example, if you have a set of routes related to user authentication, you can create a UserController.js file and define the logic for handling user authentication in that file.
Here is an example of a simple UserController.js file:
“`
// UserController.js
const User = require(‘../models/User’);
const UserController = {
getAllUsers: async (req, res) => {
try {
const users = await User.find();
res.json(users);
} catch (error) {
res.status(500).json({ message: error.message });
}
},
getUserById: async (req, res) => {
try {
const user = await User.findById(req.params.id);
res.json(user);
} catch (error) {
res.status(404).json({ message: ‘User not found’ });
}
},
createUser: async (req, res) => {
try {
const newUser = new User(req.body);
await newUser.save();
res.status(201).json(newUser);
} catch (error) {
res.status(400).json({ message: error.message });
}
}
};
module.exports = UserController;
“`
In this example, we have defined three controller methods to handle getting all users, getting a user by ID, and creating a new user. We are using the async/await syntax for handling asynchronous operations like database queries.
Using the controller in routes
Once you have created a controller, you can use it in your route definitions to handle the logic for specific endpoints. Here is an example of how to use the UserController in the route definitions:
“`
// routes.js
const express = require(‘express’);
const UserController = require(‘./controllers/UserController’);
const router = express.Router();
router.get(‘/users’, UserController.getAllUsers);
router.get(‘/users/:id’, UserController.getUserById);
router.post(‘/users’, UserController.createUser);
module.exports = router;
“`
In this example, we are using the UserController methods to handle the logic for the /users, /users/:id, and /users POST routes. This way, the route definitions remain clean and focused on defining the endpoints without cluttering them with logic.
Conclusion
Working with controllers in Express.js helps to keep your codebase organized and maintainable by separating the logic from the route definitions. By creating controllers for different sets of routes, you can easily manage and test the application’s logic in a structured way.
In the next part of this tutorial, we will explore how to use middleware in Express.js to add additional functionality to our web app.
keep up mate👌