Routes and Controllers

Define Egg.js routes, write controllers, read request parameters, and return responses while understanding each controller's responsibilities.

🎯 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.

app/router.js
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:

app/router.js
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:

app/controller/user.js
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 async and accesses the context object through this.ctx. This is the same ctx used in Koa.
  • Export the class from the file. Egg exposes its methods as controller.filename.methodName.
Egg also supports function-based handlers defined in plain objects, but its scaffold and documentation primarily use classes. This course consistently uses classes.

🧱 Reading Request Parameters

Clients generally pass data in three ways, each with a different access method:

app/controller/user.js
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:

app/controller/user.js
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:

app/router.js
module.exports = app => {
    const { router, controller } = app;
    router.resources('users', '/users', controller.user);
};

The equivalent route mappings are:

HTTP methodPathController methodDescription
GET/usersindexList users
GET/users/:idshowGet a user
POST/userscreateCreate
PUT/users/:idupdateUpdate
DELETE/users/:iddestroyDelete
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.

app/controller/goods.js
const { Controller } = require('egg');

class GoodsController extends Controller {
    async show() {
        const { ctx } = this;
        // Write your code here
    }
}

module.exports = GoodsController;
app/router.js
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.