阿里Eggjs后端框架

安裝 node

安裝你喜歡的編輯器

  • Visual studio code、
  • Atom
  • ...

本次以 Visual studio code 演示

初始化項(xiàng)目

  • 打開終端

    Ctrl+`
    
  • 輸入初始化項(xiàng)目命令

    npm init
    
  • 輸入安裝 egg 命令

    npm install egg --save
    
  • 輸入安裝 egg-dev 命令

    npm install egg-bin --save-dev
    

約定大于配置

MVC 架構(gòu)的 controller

  • 新建文件夾./app/controller/
  • 新建./app/controller/index.js

Hello world

  • 拿到 egg 對(duì)象

    const egg = require("egg");
    
  • 拿到 Controller 基類

    const Controller = egg.Controller;
    
  • 基于 Controller 基類寫一個(gè)自己的 Controller 類

    class HomeController extends Controller {}
    module.exports = HomeController;
    
  • 在自己 Controller 類中寫一個(gè)控制器函數(shù)

    class HomeController extends Controller {
      async index() {
        this.ctx.body = "Hello world";
      }
    }
    

路由

  • 新建./app/router.js

  • 開始撰寫要導(dǎo)出路由模塊

    module.exports = (app) => {};
    
  • 開始撰寫要導(dǎo)出路由模塊

    module.exports = (app) => {
      const { router, controller } = app;
      router.get("/", controller.index.index);
    };
    

egg.ctx

  • 繼續(xù)撰寫如下 controller

    class HomeController extends Controller {
      async index() {
        this.ctx.body = "Hello world";
      }
      async about() {
        this.ctx.body = "這個(gè)是關(guān)于";
      }
      async get() {
        this.ctx.body = {
          url: this.ctx.url,
          method: this.ctx.method,
          query: this.ctx.query
        };
      }
      async getId() {
        this.ctx.body = {
          id: this.ctx.params.id,
          url: this.ctx.url,
          method: this.ctx.method,
          query: this.ctx.query
        };
      }
    }
    
  • 繼續(xù)撰寫如下路由

    module.exports = app => {
      const { router, controller } = app;
      router.get("/", controller.index.index);
      router.get("/about", controller.index.about);
      router.get("/get", controller.index.get);
      router.get("/getid/:id", controller.index.getId);
    };
    
  • 進(jìn)行測(cè)試

  • 打開

    http://host:port/
    
  • 打開

    http://host:port/about
    
  • 打開

    http://host:port/get?page=5&number=10
    
  • 打開

    http://host:port/getid/1234567?page=5&number=10
    

靜態(tài)資源服務(wù)器

  • 安裝靜態(tài)資源服務(wù)插件

    npm i egg-static --save
    
  • 打開

    http://host:port/public/index.html
    
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容