egg學習筆記第十四天:eggjs控制器基類BaseController、控制器兼容寫法

1、實現一個小功能,首頁是登陸註冊按鈕,點擊跳轉到對應頁面進行登陸or註冊操做,成功跳轉到對應成功or失敗頁面,3s後再返回首頁。相似於淘寶支付完成以後的效果。則:

①配置/login /register /doLogin /doRegister路由javascript

"use strict";

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

②改造home>index方法,渲染home模板(前提配置ejs)html

"use strict";

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

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    await ctx.render("home");
  }
}

module.exports = HomeController;

③編寫user controllerjava

"use strict";

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

class UserController extends Controller {
  async login() {
    const { ctx } = this;
    await ctx.render("login");
  }
  async register() {
    const { ctx } = this;
    await ctx.render("register");
  }
  async doLogin() {
    const { ctx } = this;
    console.log(ctx.request.body);
    await ctx.render("public/success", {
      url: "/"
    });
  }
  async doRegister() {
    const { ctx } = this;
    console.log(ctx.request.body);
    await ctx.render("public/error", {
      url: "/"
    });
  }
}

module.exports = UserController;

④編寫設置全局模板csrf值得中間件並配置。es6

module.exports = (option, app) => {
  return async function auth(ctx, next) {
    //設置模板全局變量
    ctx.state.csrf = ctx.csrf;
    await next();
  };
};

config.middleware = ["auth"];

⑤配置5個模板app

error.htmlasync

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
  </head>
  <body>
    <h1 style="color:red">登陸失敗...3s後自動跳轉</h1>

  </body>
</html>

 

success.htmlpost

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta http-equiv="refresh" content="3;url=/">
    <title>Document</title>
  </head>
  <body>
    <h1 style="color:green">登錄成功...3s後自動跳轉</h1>
  </body>
</html>

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
  </head>
  <body>
    <h2>
      eggjs控制器基類BaseController演示
    </h2>
    <a href="/login">登陸</a>

    <a href="/register">註冊</a>
  </body>
</html>

login.htmlui

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>登陸頁面</title>
  </head>
  <body>
    <h2>登陸頁面</h2>
    <form action="/doLogin" method="POST">
      <input type="hidden" name="_csrf" value="<%=csrf%>">
      用戶名:<input type="text" name="username"><br>
      密碼:<input type="password" name="password"><br>
      <button type="submit">提交</button>

    </form>
  </body>
</html>

register.html:this

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>註冊頁面</title>
  </head>
  <body>
    <h2>註冊頁面</h2>
    <form action="/doRegister" method="POST">
      <input type="hidden" name="_csrf" value="<%=csrf%>">
      用戶名:<input type="text" name="username"><br>
      密碼:<input type="password" name="password"><br>
      <button type="submit">提交</button>

    </form>
  </body>
</html>

以上操做步驟可實現上述效果。注意 這句meta標籤能夠實現3s跳轉到/url

<meta http-equiv="refresh" content="3;url=/">

隨後咱們發現若是不少頁面都須要跳轉success或者error頁面,代碼會顯得十分冗雜,因此咱們能夠經過es6中繼承的方式封裝controller基類。

 

2、eggjs控制器基類BaseController

按照類的方式編寫Controller,不只可讓咱們更好的對Controller層代碼進行抽象(例如將一些統一的處理抽象成一些私有方法),還能夠經過自定義Controller基類的方式封裝應用中的經常使用方法,因此咱們能夠將以上代碼作一些改造:

① app下新建core文件夾,在新建base.js,鍵入:導出一個基類,寫入一些公共方法。

"use strict";

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

class BaseController extends Controller {
  async getUserInfo() {
    const { ctx } = this;
    return {
      name: "董文傑",
      age: 18
    };
  }
  async success(redirectUrl) {
    const { ctx } = this;
    await ctx.render("public/success", {
      redirectUrl
    });
  }
  async error(redirectUrl) {
    const { ctx } = this;
    await ctx.render("public/error", {
      redirectUrl
    });
  }
}

module.exports = BaseController;

②在user controller作改造,引入基類,並繼承基類,也能實現上述效果,並且代碼會顯得很清晰

"use strict";

// const Controller = require("egg").Controller;
const BaseController = require("../core/base");
class UserController extends BaseController {
  async login() {
    const { ctx } = this;
    await ctx.render("login");
  }
  async register() {
    const { ctx } = this;
    await ctx.render("register");
  }
  async doLogin() {
    await this.success("/");
  }
  async doRegister() {
    await this.error("/");
  }
}

module.exports = UserController;

 

3、控制器兼容性寫法

這倆是同樣的效果,官方推薦第一種。

出去玩咯。

相關文章
相關標籤/搜索