title: Router

Router is mainly used to describe the corresponding relationship between the request URL and the Controller that processes the request eventually. All routing rules are unified in the app/router.js file by the framework.

By unifying routing rules, we can avoid the routing logics scattered in many places which may cause many unknown conflicts, and we can more easily check global routing rules.

How to Define Router

  • Define the routing rule in app/router.js file
  1. // app/router.js
  2. module.exports = app => {
  3. const { router, controller } = app;
  4. router.get('/user/:id', controller.user.info);
  5. };
  • Implement the Controller in app/controller directory
  1. // app/controller/user.js
  2. class UserController extends Controller {
  3. async info() {
  4. const { ctx } = this;
  5. ctx.body = {
  6. name: `hello ${ctx.params.id}`,
  7. };
  8. }
  9. }

This simplest Router is done by now, when users do the request GET /user/123, the info function in user.js will be invoked.

Router config in detail

Below is the complete definition of router, parameters can be determined depending on different scenes.

  1. router.verb('path-match', app.controller.action);
  2. router.verb('router-name', 'path-match', app.controller.action);
  3. router.verb('path-match', middleware1, ..., middlewareN, app.controller.action);
  4. router.verb('router-name', 'path-match', middleware1, ..., middlewareN, app.controller.action);

The complete definition of router includes 5 major parts:

  • verb - actions that users trigger, including get, post and so on, and will be explained in detail later.
    • router.head - HEAD
    • router.options - OPTIONS
    • router.get - GET
    • router.put - PUT
    • router.post - POST
    • router.patch - PATCH
    • router.delete - DELETE
    • router.del - this is a alias method due to the reservation of delete.
    • router.redirect - redirects the request URL. For example, the most common case is to redirect the request accessing the root directory to the homepage.
  • router-name defines a alias for the route, and URL can be generated by helper method pathFor and urlFor provided by Helper. (Optional)
  • path-match - URL path of the route.
  • middleware1 - multiple Middlewares can be configured in Router. (Optional)
  • controller - set the route to map to the specific controller, and the controller can be written in two types:
    • app.controller.user.fetch - directly point to a controller
    • 'user.fetch' - simplified as a string,

Notices

  • multiple Middlewares can be configured to execute serially in Router definition
  • Controller must be defined under app/controller directory
  • multiple Controllers can be defined within one file, and the specific one can be specified in the form of ${fileName}.${functionName} when defining the routing rule.
  • Controller supports sub-directories, and the specific one can be specified in the form of ${directoryName}.${fileName}.${functionName} when defining the routing rule.

Here are some examples of writing routing rules:

  1. // app/router.js
  2. module.exports = app => {
  3. const { router, controller } = app;
  4. router.get('/home', controller.home);
  5. router.get('/user/:id', controller.user.page);
  6. router.post('/admin', isAdmin, controller.admin);
  7. router.post('/user', isLoginUser, hasAdminPermission, controller.user.create);
  8. router.post('/api/v1/comments', controller.v1.comments.create); // app/controller/v1/comments.js
  9. };

RESTful style URL definition

We provide app.resources('routerName', 'pathMatch', 'controller') to generate CRUD structures on a path for convenience if you prefer the RESTful style URL definition.

  1. // app/router.js
  2. module.exports = app => {
  3. const { router, controller } = app;
  4. router.resources('posts', '/posts', controller.posts);
  5. router.resources('users', '/api/v1/users', controller.v1.users); // app/controller/v1/users.js
  6. };

The codes above produce a bunch of CRUD path structures for Controller app/controller/posts.js, and the only thing you should do next is to implement related functions in posts.js.

Method Path Route Name Controller.Action
GET /posts posts app.controllers.posts.index
GET /posts/new new_post app.controllers.posts.new
GET /posts/:id post app.controllers.posts.show
GET /posts/:id/edit edit_post app.controllers.posts.edit
POST /posts posts app.controllers.posts.create
PATCH /posts/:id post app.controllers.posts.update
DELETE /posts/:id post app.controllers.posts.destroy
  1. // app/controller/posts.js
  2. exports.index = async () => {};
  3. exports.new = async () => {};
  4. exports.create = async () => {};
  5. exports.show = async () => {};
  6. exports.edit = async () => {};
  7. exports.update = async () => {};
  8. exports.destroy = async () => {};

Methods that are not needed may not be implemented in posts.js and the related URL paths will not be registered to Router neither.

Router in Action

More practical examples will be shown below to demonstrate how to use the router.

Acquiring Parameters

via Query String

  1. // app/router.js
  2. module.exports = app => {
  3. app.router.get('/search', app.controller.search.index);
  4. };
  5. // app/controller/search.js
  6. exports.index = async ctx => {
  7. ctx.body = `search: ${ctx.query.name}`;
  8. };
  9. // curl http://127.0.0.1:7001/search?name=egg

via Named Parameters

  1. // app/router.js
  2. module.exports = app => {
  3. app.router.get('/user/:id/:name', app.controller.user.info);
  4. };
  5. // app/controller/user.js
  6. exports.info = async ctx => {
  7. ctx.body = `user: ${ctx.params.id}, ${ctx.params.name}`;
  8. };
  9. // curl http://127.0.0.1:7001/user/123/xiaoming

acquiring complex parameters

Regular expressions, as well, can be used in routing rules to acquire parameters more flexibly:

  1. // app/router.js
  2. module.exports = app => {
  3. app.router.get(/^\/package\/([\w-.]+\/[\w-.]+)$/, app.controller.package.detail);
  4. };
  5. // app/controller/package.js
  6. exports.detail = async ctx => {
  7. // If the request URL is matched by the regular expression, parameters can be acquired from ctx.params according to the capture group orders.
  8. // For the user request below, for example, the value of `ctx.params[0]` is `egg/1.0.0`
  9. ctx.body = `package:${ctx.params[0]}`;
  10. };
  11. // curl http://127.0.0.1:7001/package/egg/1.0.0

Acquiring Form Contents

  1. // app/router.js
  2. module.exports = app => {
  3. app.router.post('/form', app.controller.form.post);
  4. };
  5. // app/controller/form.js
  6. exports.post = async ctx => {
  7. ctx.body = `body: ${JSON.stringify(ctx.request.body)}`;
  8. };
  9. // simulate a post request.
  10. // curl -X POST http://127.0.0.1:7001/form --data '{"name":"controller"}' --header 'Content-Type:application/json'

P.S.:

If you perform a POST request directly, an error will occur: ‘secret is missing’. This error message comes from koa-csrf/index.js#L69.

Reason: the framework verifies the CSFR value specially for form POST requests, so please submit the CSRF key as well when you submit a form. Refer to Keep Away from CSRF Threat for more detail.

Note: the verification is performed because the framework builds in a security plugin egg-security that provides some default security practices and this plugin is enabled by default. In case you want to disable some security protections, just set the enable attribute to false.

“Unless you clearly confirm the consequence, it’s not recommended to disable functions provided by the security plugin”

Here we do the config temporarily in config/config.default.js for an example

  1. exports.security = {
  2. csrf: false
  3. };

Form Verification

  1. // app/router.js
  2. module.exports = app => {
  3. app.router.post('/user', app.controller.user);
  4. };
  5. // app/controller/user.js
  6. const createRule = {
  7. username: {
  8. type: 'email',
  9. },
  10. password: {
  11. type: 'password',
  12. compare: 're-password',
  13. },
  14. };
  15. exports.create = async ctx => {
  16. // throws exceptions if the verification fails
  17. ctx.validate(createRule);
  18. ctx.body = ctx.request.body;
  19. };
  20. // curl -X POST http://127.0.0.1:7001/user --data 'username=abc@abc.com&password=111111&re-password=111111'

Redirection

Internal Redirection

  1. // app/router.js
  2. module.exports = app => {
  3. app.router.get('index', '/home/index', app.controller.home.index);
  4. app.redirect('/', '/home/index', 302);
  5. };
  6. // app/controller/home.js
  7. exports.index = async ctx => {
  8. ctx.body = 'hello controller';
  9. };
  10. // curl -L http://localhost:7001

External Redirection

  1. // app/router.js
  2. module.exports = app => {
  3. app.router.get('/search', app.controller.search.index);
  4. };
  5. // app/controller/search.js
  6. exports.index = async ctx => {
  7. const type = ctx.query.type;
  8. const q = ctx.query.q || 'nodejs';
  9. if (type === 'bing') {
  10. ctx.redirect(`http://cn.bing.com/search?q=${q}`);
  11. } else {
  12. ctx.redirect(`https://www.google.co.kr/search?q=${q}`);
  13. }
  14. };
  15. // curl http://localhost:7001/search?type=bing&q=node.js
  16. // curl http://localhost:7001/search?q=node.js

Using Middleware

A middleware can be used to change the request parameter to uppercase.
Here we just briefly explain how to use the middleware, and refer to Middleware for detail.

  1. // app/controller/search.js
  2. exports.index = async ctx => {
  3. ctx.body = `search: ${ctx.query.name}`;
  4. };
  5. // app/middleware/uppercase.js
  6. module.exports = () => {
  7. return async function uppercase(ctx, next) {
  8. ctx.query.name = ctx.query.name && ctx.query.name.toUpperCase();
  9. await next();
  10. };
  11. };
  12. // app/router.js
  13. module.exports = app => {
  14. app.router.get('s', '/search', app.middlewares.uppercase(), app.controller.search)
  15. };
  16. // curl http://localhost:7001/search?name=egg

Too Many Routing Maps?

As described above, we do not recommend that you scatter routing logics all around, or it will bring trouble in trouble shooting.

If there is a need for some reasons, you can split routing rules like below:

  1. // app/router.js
  2. module.exports = app => {
  3. require('./router/news')(app);
  4. require('./router/admin')(app);
  5. };
  6. // app/router/news.js
  7. module.exports = app => {
  8. app.router.get('/news/list', app.controller.news.list);
  9. app.router.get('/news/detail', app.controller.news.detail);
  10. };
  11. // app/router/admin.js
  12. module.exports = app => {
  13. app.router.get('/admin/user', app.controller.admin.user);
  14. app.router.get('/admin/log', app.controller.admin.log);
  15. };

or using egg-router-plus.