Routes and Controllers
🎯 Introduction
By the end of this article, you will be able to define routes for different HTTP methods in router.js, read path parameters, query parameters, and request bodies in controllers, and return data with appropriate status codes. You will also understand what belongs in a controller.
🧱 What Is a Route?
A route answers one question: which handler should process a request for a particular URL?
In the Node.js course, we implemented simple routing with conditions on req.url. Egg standardizes this approach: routes go in app/router.js, and their handlers go in controllers.
module.exports = app => {
const { router, controller } = app;
router.get('/users', controller.user.index);
};
controller.user.index refers to the index method in app/controller/user.js. By convention, the filename determines how the controller is exposed, without a manual import.
🛠 Common HTTP Methods
router supports methods such as GET, POST, PUT, and DELETE, each corresponding to an HTTP method:
module.exports = app => {
const { router, controller } = app;
router.get('/users', controller.user.index); // List users
router.get('/users/:id', controller.user.show); // Get a user
router.post('/users', controller.user.create); // Create
router.put('/users/:id', controller.user.update); // Update
router.delete('/users/:id', controller.user.destroy); // Delete
};
In /users/:id, :id is a path parameter, a dynamic segment whose value you can read in the controller.
🧱 Writing a Controller
Egg recommends writing controllers as classes that extend Controller:
const { Controller } = require('egg');
class UserController extends Controller {
async index() {
const { ctx } = this;
ctx.body = 'User list';
}
}
module.exports = UserController;
There are two key points:
- Each method is
asyncand accesses the context object throughthis.ctx. This is the samectxused in Koa. - Export the class from the file. Egg exposes its methods as
controller.filename.methodName.
🧱 Reading Request Parameters
Clients generally pass data in three ways, each with a different access method:
class UserController extends Controller {
async show() {
const { ctx } = this;
// 1. Path parameter: the 1 in GET /users/1
const id = ctx.params.id;
// 2. Query parameter: keyword in GET /users?keyword=Ming
const keyword = ctx.query.keyword;
ctx.body = { id, keyword };
}
async create() {
const { ctx } = this;
// 3. Request body: data submitted with POST
const data = ctx.request.body;
ctx.body = { receivedData: data };
}
}
ctx.request.body relies on the built-in bodyParser capability. Include the Content-Type: application/json header when sending JSON, or the parsed data may not be available.Values read from ctx.params and ctx.query are strings. For example, ctx.params.id returns '1'; convert it explicitly when you need a number.
🧱 Returning Responses and Status Codes
Assign a value to ctx.body to return a response. Objects are automatically serialized as JSON. Set the status code with ctx.status:
class UserController extends Controller {
async create() {
const { ctx } = this;
const user = { id: 1, name: ctx.request.body.name };
// Return 201 for successful creation, following REST conventions
ctx.status = 201;
ctx.body = user;
}
async show() {
const { ctx } = this;
if (ctx.params.id === '999') {
// Return 404 when the resource does not exist
ctx.status = 404;
ctx.body = { message: 'User not found' };
return;
}
ctx.body = { id: ctx.params.id, name: 'Ming' };
}
}
Common status codes include 200 for success, 201 for creation, 400 for invalid parameters, 404 for a missing resource, and 500 for a server error.
💡 RESTful Routing with router.resources
The five routes above are a standard pattern for user management. Egg provides a shorthand to register them in one line:
module.exports = app => {
const { router, controller } = app;
router.resources('users', '/users', controller.user);
};
The equivalent route mappings are:
| HTTP method | Path | Controller method | Description |
|---|---|---|---|
| GET | /users | index | List users |
| GET | /users/:id | show | Get a user |
| POST | /users | create | Create |
| PUT | /users/:id | update | Update |
| DELETE | /users/:id | destroy | Delete |
resources also registers new and edit routes for rendering pages. An API-only application does not need them; implement only the five controller methods you use.🪤 A Controller's Responsibilities
It is easy to put everything in a controller when starting out. A well-structured controller handles only four tasks:
- Receive the request: Read parameters from
ctx. - Validate parameters: Check that the required values are present and valid.
- Call a service: Delegate business operations to the service layer.
- Return the result: Prepare the data and set the response.
Business logic, such as retrieving and processing data, belongs in the service layer. Keeping controllers lean makes the project easier to maintain, which is the topic of the next article.
❓ Questions and Answers
Q1: What is the difference between ctx.params and ctx.query?
ctx.params reads dynamic path segments, such as id in /users/:id. ctx.query reads the query string after the question mark, such as page in /users?page=2. Both return strings.
Q2: Why is ctx.request.body sometimes an empty object?
A common cause is a missing Content-Type: application/json header, leaving bodyParser without the expected format information. Remember to include it when using curl, Apifox, or frontend code.
Q3: Must controller methods be named index, show, and create?
With explicit router.get calls, you can choose any method name. With router.resources, use the conventional index/show/create/update/destroy names so Egg can map the routes correctly.
Q4: Can a route use a callback directly instead of a controller?
Technically yes, but that does not follow Egg's conventions. Routing requests through controllers keeps the project consistent and makes it easier to add services, middleware, and other capabilities later.
🧪 Exercise
Add a goods module: define GET /goods/:id, read both the id path parameter and the from query parameter in its controller, and return them as JSON.
const { Controller } = require('egg');
class GoodsController extends Controller {
async show() {
const { ctx } = this;
// Write your code here
}
}
module.exports = GoodsController;
module.exports = app => {
const { router, controller } = app;
router.get('/', controller.home.index);
// Write your code here
};
🎉 You now know how to use routes and controllers! Next, we will move business logic into services to give the project a clearer structure.
