Day 13 of egg learning notes: several writing methods of eggjs route, route redirection, route grouping (route mapping)

1, Several writing methods of eggjs route configuration.

https://eggjs.org/zh-cn/basics/router.html#router-%E8%AF%A6%E7%BB%86%E5%AE%9A%E4%B9%89%E8%AF%B4%E6%98%8E

The following is the complete definition of route. Parameters can be freely selected according to different scenarios:

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

The complete definition of route mainly includes five parts:

  • verb - user triggered actions, support get, post and other HTTP methods.
    • router.head - HEAD
    • router.options - OPTIONS
    • router.get - GET
    • router.put - PUT
    • router.post - POST
    • router.patch - PATCH
    • router.delete - DELETE
    • router.del - since delete is a reserved word, an alias for the delete method is provided.
    • router.redirect - redirect URL s, such as the one we use most often to route users' access to a home page.
  • Router name sets an alias for the route. You can generate the URL through the Helper's auxiliary functions pathFor and urlFor. (optional)
  • Path match - route URL path.
  • middleware1 - multiple middleware can be configured in the Router. (optional)
  • Controller - specifies the specific controller to which the route is mapped. The controller can be written in two ways:
    • app.controller.user.fetch - specify a specific controller directly
    • 'user.fetch' - can be abbreviated to string

① The simplest one: a path, a method under the controller.

router.get("/admin/user", controller.admin.user.index);

② Second, add the writing method of one or more middleware.

var adminAuth = app.middleware.adminAuth();
var adminAuth1 = app.middleware.adminAuth1();

router.get("/admin/user", adminAuth, adminAuth1, controller.admin.user.index);

③ Name the route. The first parameter can give a name to the current route. If you want to access it, you need to use the second parameter path.

router.get("apiuser", "/api/user", controller.api.user.index);

2, eggjs route redirection. It's good for seo optimization. If a site is hung and redirected, the previous site will not be deleted.

301 permanent redirection 302 temporary redirection

 

① Route internal redirection. Personal understanding is to configure redirection when router.js is configured. app.router.redirect()

// app/router.js
module.exports = app => {
  app.router.get('index', '/home/index', app.controller.home.index);
  app.router.redirect('/', '/home/index', 302);
};

// app/controller/home.js
exports.index = async ctx => {
  ctx.body = 'hello controller';
};

// curl -L http://localhost:7001

② Route external redirects, such as yesterday's authentication middleware.

module.exports = (option, app) => {
  return async function auth(ctx, next) {
    // If the session exists, it means continue to access by login. If the session does not exist, it means no login. Go to the home page
    if (ctx.session && ctx.session.userInfo) {
      await next();
    } else {
      if (ctx.request.url == "/") {
        await next();
      } else {
        ctx.redirect("/");
      }
    }
  };
};

Or in a controller, you can use ctx.redirect()

// app/router.js
module.exports = app => {
  app.router.get('/search', app.controller.search.index);
};

// app/controller/search.js
exports.index = async ctx => {
  const type = ctx.query.type;
  const q = ctx.query.q || 'nodejs';

  if (type === 'bing') {
    ctx.redirect(`http://cn.bing.com/search?q=${q}`);
  } else {
    ctx.redirect(`https://www.google.co.kr/search?q=${q}`);
  }
};

// curl http://localhost:7001/search?type=bing&q=node.js
// curl http://localhost:7001/search?q=node.js

The default is temporary redirection. For example, to access / api/user in a project, you need to temporarily redirect to / api/product. Then, use external redirection to type in the index method under the user controller:

"use strict";

const Controller = require("egg").Controller;

class UserController extends Controller {
  async index() {
    const { ctx } = this;
    ctx.redirect("/api/product");
    ctx.body = "user api Interface";
  }
}

module.exports = UserController;

The results of accessing / api/user are as follows:

For permanent redirection, make some changes:

"use strict";

const Controller = require("egg").Controller;

class UserController extends Controller {
  async index() {
    const { ctx } = this;
    ctx.status = 301; 
    ctx.redirect("/api/product");
    ctx.body = "user api Interface";
  }
}

module.exports = UserController;

Status code changed to 301

Or the internal redirection is configured in router.js as follows: the redirection effect can also be achieved. Note: there may be cache in redirection, and the browser cache needs to be cleared during testing

3, Route grouping (route mapping)

When the project is relatively large, it will be very miscellaneous to write routes in router.js, which is not easy to manage. Therefore, we need to split the routing module. I think the idea of route splitting here is also applicable to the front-end vue or react project.

So we can be divided into three modules for routing transformation.

Create a new routes folder under app, a new admin.js api.js index.js, and type in the post management, API, and front-end route configurations

admin.js:

api.js

"use strict";

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller } = app;

  // api
  router.get("/api/user", controller.api.user.index);
  router.redirect("/api/user", "/api/product", 302);
  router.get("/api/product", controller.api.product.index);
};

 

index.js

"use strict";

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller } = app;
  router.get("/", controller.home.index);
};

 

To modify the router.js file:

"use strict";

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  // Rear tube
  require("./routes/admin")(app);

  // api interface
  require("./routes/api")(app);

  // Reception
  require("./routes/index")(app);
};

It can be seen from this that the routing management module is very clear. It can be seen from the visit that the routing configuration is still in effect. It's a bit of the meaning of the principle of single responsibility. Bang Bang Da, hit two kings.

Tags: Front-end Session curl Google Vue

Posted on Fri, 17 Apr 2020 05:07:47 -0700 by gskaruz