Day 12 of egg learning notes: eggjs combines simple project to realize routing grouping and loading middleware on demand

Keywords: Front-end Session

1, Mind map of a normal project

It is roughly divided into three parts:

① Background management system (login required)

② Website front desk

3. api interface

The following is an example of module grouping based on Routing and controller:

"use strict";

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

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

  router.get("/admin/article", controller.admin.article.index);
  router.get("/admin/article/add", controller.admin.article.add);
  router.get("/admin/article/edit", controller.admin.article.edit);

  router.get("/admin/product", controller.admin.product.index);
  router.get("/admin/product/add", controller.admin.product.add);
  router.get("/admin/product/edit", controller.admin.product.edit);

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

 

2, A middleware is needed for the authentication of the back management system before login.

① Create admin_auth.js under middleware, and write the following:

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("/");
      }
    }
  };
};

② Configure the middleware to take effect.

  config.middleware = ["adminAuth"];

③ The middleware configuration is complete, but accessing all URLs will execute the middleware. If you need to execute on demand, you only want to execute when accessing the post management, then:

Note out the middleware configuration in config > config.default.js, introduce Middleware in router.js and register locally, and write the second parameter in each reason rule:

 

② Another way is to configure match for middleware.

// add your middleware config here
  config.middleware = ["adminAuth"];
  config.adminAuth = {
    match: "/admin"
  };

Every path with '/ admin' will execute adminAuth middleware. So a post management system can simulate the authentication effect most simply.

Posted by edraynham on Thu, 16 Apr 2020 07:14:09 -0700