Creating Routes and Controllers
Creating Routes and Controllers in Express.js
In any web application or API, routing and controllers play an essential role in managing how requests are processed. Routes define the endpoints and the HTTP methods that clients use to interact with the server, while controllers handle the logic of processing those requests. In Express.js, creating routes and controllers is straightforward, allowing you to keep your application well-structured and maintainable.
In this article, we will explore how to set up routes and controllers in Express.js, and how to organize your code for better scalability and ease of maintenance.
What Are Routes and Controllers?
- Routes: In Express, routes are the paths that define where an API request should be directed. Each route is tied to a specific HTTP method (GET, POST, PUT, DELETE, etc.) and a URL path, and they map to specific functions or controller methods that process those requests.
- Controllers: A controller is a function or a module that contains the logic for processing incoming requests. It handles actions like fetching data from a database, performing calculations, or updating resources.
By separating routes from controllers, you can organize your application into clear, manageable sections, where routes define the structure and controllers contain the application logic.
Step 1: Setting Up a Basic Express Application
Before diving into routes and controllers, let’s set up a simple Express.js application:
- Initialize a new Node.js project:
npm init -y
- Install Express.js:
npm install express
- Create a file called
app.js
:const express = require('express'); const app = express(); const port = 3000; app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });
Now you have a basic Express server running on port 3000
.
Step 2: Creating Routes
Routes are defined using Express’s routing methods such as app.get()
, app.post()
, app.put()
, and app.delete()
. These methods map HTTP requests to specific URL paths and associate them with a function that handles the request.
Let’s start by defining some basic routes for an API that manages users.
const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());
// Simple route to handle GET requests
app.get('/users', (req, res) => {
res.json({ message: "Get list of users" });
});
// Route to handle POST requests for creating a user
app.post('/users', (req, res) => {
const user = req.body;
res.status(201).json({ message: "User created", user: user });
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
Explanation:
app.get('/users')
: Defines a GET route for fetching the list of users.app.post('/users')
: Defines a POST route for creating a new user.
Step 3: Organizing Code with Controllers
As your application grows, it’s a good practice to separate your route handlers into controller functions. This helps in maintaining clean, manageable code, especially in larger applications.
Let’s create a simple controller for managing users.
- Create a
controllers
directory and inside it, create a file calleduserController.js
. - Define the controller methods:
// controllers/userController.js
const getUsers = (req, res) => {
res.json({ message: "Get list of users" });
};
const createUser = (req, res) => {
const user = req.body;
res.status(201).json({ message: "User created", user: user });
};
module.exports = { getUsers, createUser };
Step 4: Import and Use Controllers in Routes
Now that you have defined your controller functions, you can import them into your app.js
and use them in your routes.
- Update
app.js
to use the controller methods:
const express = require('express');
const app = express();
const port = 3000;
// Importing controller functions
const userController = require('./controllers/userController');
app.use(express.json());
// Define routes and associate them with controller methods
app.get('/users', userController.getUsers);
app.post('/users', userController.createUser);
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
Explanation:
require('./controllers/userController')
: This imports the controller methods from theuserController.js
file.app.get('/users', userController.getUsers)
: This associates the GET route for/users
with thegetUsers
method from the controller.app.post('/users', userController.createUser)
: This associates the POST route for/users
with thecreateUser
method from the controller.
Step 5: Adding Additional Routes and Controllers
As your application grows, you will add more resources and more routes. Here’s how you can expand the structure by adding more routes for updating and deleting users.
- Update the
userController.js
to include update and delete operations:
// controllers/userController.js
const getUsers = (req, res) => {
res.json({ message: "Get list of users" });
};
const createUser = (req, res) => {
const user = req.body;
res.status(201).json({ message: "User created", user: user });
};
const updateUser = (req, res) => {
const { id } = req.params;
const updatedUser = req.body;
res.json({ message: `User ${id} updated`, user: updatedUser });
};
const deleteUser = (req, res) => {
const { id } = req.params;
res.json({ message: `User ${id} deleted` });
};
module.exports = { getUsers, createUser, updateUser, deleteUser };
- Update
app.js
to include the new routes:
const express = require('express');
const app = express();
const port = 3000;
// Import controller functions
const userController = require('./controllers/userController');
app.use(express.json());
// Define routes and associate them with controller methods
app.get('/users', userController.getUsers);
app.post('/users', userController.createUser);
app.put('/users/:id', userController.updateUser);
app.delete('/users/:id', userController.deleteUser);
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
Explanation:
app.put('/users/:id', userController.updateUser)
: Updates a specific user by their ID.app.delete('/users/:id', userController.deleteUser)
: Deletes a user by their ID.
Step 6: Testing Your API
To test your routes:
- Use Postman or cURL to send GET, POST, PUT, and DELETE requests to
http://localhost:3000/users
. - Make sure to test creating a user (POST), retrieving users (GET), updating a user (PUT), and deleting a user (DELETE).
Conclusion
In this article, we covered the process of creating routes and controllers in Express.js:
- Routes are used to define URL endpoints and HTTP methods.
- Controllers handle the logic for processing the requests and interacting with the resources.
- By separating routes and controllers, your code becomes more modular, scalable, and easier to maintain.
This structure is fundamental for building clean, organized RESTful APIs with Express.js.