一.Egg.JS 簡介
Egg.JS是阿里開發的一套node.JS的框架,主要以下幾個特點:
- Egg 的插件機制有很高的可擴展性,一個插件只做一件事,Egg 通過框架聚合這些插件,並根據自己的業務場景定制配置,這樣應用的開發成本就變得很低。
- Egg 奉行『約定優於配置』,目錄名稱規范,團隊內部采用這種方式可以減少開發人員的學習成本,
- Node.遵循MVC框架
Mode 層對應server文件夾
View 層 對應view文件
Controller 對應 Controller文件夾
4.其他
提供基於 Egg 定制上層框架的能力,
高度可擴展的插件機制
內置多進程管理
基於 Koa 開發,性能優異
框架穩定,測試覆蓋率高
漸進式開發

創建項目
cnpm i egg-init -g
egg-init spider --type=simple
cd spider
cnpm i
二.Egg快速編輯插件Vscode+egg的安裝和使用


安裝完成egg controller即可一鍵輸出controller基本結構
Service,config ,plugin同理,生成controller
'use strict'; const Controller = require('egg').Controller; class ListController extends Controller { async echo() { } } module.exports = ListController;
Egg.JS的目錄結構如下

三、為好的使用egg安裝ejs模板
模板地址: https://www.npmjs.com/package/egg-view
cnpm install egg-view-ejs --save
ejs配置
修改文件//config/plugin.js
'use strict'; exports.ejs = { enable: true, package: 'egg-view-ejs', };
修改文件//config/config.default
config.view = { mapping: { '.html': 'ejs', }, };
修改//constroller/new.js
async index() { let name = this.ctx.query.name; //query接收動態數據 let id = this.ctx.params.id; //params接收路由傳值 let list = [1,2,3]; // 修改加載ejs的方式 await this.ctx.render('news',{name,id,list}) } module.exports = NewsController;
四. 動態參數的讀取get,query傳值和params傳值
4.1 Constroller里寫
let name = this.ctx.query.name; //query接收動態數據 let id = this.ctx.params.id; //params接收路由傳值
4.2 Router文件動態配置id參數
router.get('/news', controller.news.index); router.get('/news/:id', controller.news.index);
4.3 模板文件解析參數的寫法view/news.html
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="/public/css/basic.css"> <title>Document</title></head><body> <p>query:<%= name %></p> <p>params<%= id %></p> <ul> <% for(var i=0;i<list.length;i++){ %> <li><%= list[i]%></li> <% } %> </ul> <img src="/public/img/timg.jpg"/> </body> </html>

五. Server文件的封裝
Server的封裝是為了數據在多個Constroller中都可以用到,以達到一次渲染多處調用的目的

在service下面新建 new.js 並在里面建 list服務
'use strict'; const Service = require('egg').Service; class NewsService extends Service { async list() { let list = [1,2,3,4]; return list } } module.exports = NewsService;
Server在controller中的引用
let list = await this.service.news.list(); //service的引用
六. Egg插件機制的使用
新建extend文件夾 Extend提供的擴展功能
application
context
helper //工具方法
request
在extend目錄下新建helper.js
Application.js 掛載app的方法
/* 外部可以通過 this.app.foo() */ module.exports = { foo(param) { // this 就是 app 對象,在其中可以調用 app 上的其他方法,屬性 // console.log(this); return this.config.api; }, };
Context.js
/* 外部可以通過 this.ctx.getHost() */ module.exports={ getHost(){ // this 就是 ctx 對象,在其中可以調用 ctx 上的其他方法,或訪問屬性 return this.request.host; } }
Helper.JS 工具函數類
module.exports = { formatDate(time) { return time+100 } } //在view下的html文件中的調用方式 <%= helper.formatDate(list[i].dateline)%>
Request.js 請求
/*外部可以通過 this.ctx.request.foo()*/ module.exports = { foo(param) { // console.log(this); return this.header.host; }, };
七. Egg中間件middleware
中間件:匹配路由前、匹配路由完成做的一系列的操作。 Egg 是基於 Koa 實現的,所以 Egg 的中間件形式和 Koa 的中間件形式是一樣的,都是基於洋蔥圈模型
Egg中間件放置在 app/middleware 目錄下的單獨文件,它需要 exports 一個普通的 function,接受兩個參數:
options: 中間件的配置項,框架會將 app.config[${middlewareName}] 傳遞進來。
app: 當前應用 Application 的實例。
1、app/middleware下面新建forbidip.js 內容如下:
module.exports = (options, app) => { return async function forbidipMiddleware(ctx, next) { console.log(options); //傳過來的參數 console.log(ctx.request.ip); //獲取當前的ip var sourceIp=ctx.request.ip; const match = options.ip.some(val =>{ if(val==sourceIp){ return true; } }); if (match) { ctx.status = 403; ctx.message = 'Go away, robot.'; } else { await next(); } } };
2、找到config.default.js配置當前項目需要使用的中間件以及中間件的參數
//中間件 config.middleware = ['forbidip']; config.forbidip = { ip: [ '127.0.0.1', '192.168.0.1' ], };
八. Egg中間件post提交數據安全,csrf的防范機制
所有post請求需要引入 csrf
async forms() { await this.ctx.render('forms'{csrf:this.ctx.csrf}) }
<form action="/add?_csrf=<%=csrf%>" method="post"> <!-- <input type="text" type="hidden" name="csrf" value="<%=csrf%>"> --> 用戶名: <input type="text" name="username"><br/> 密碼: <input type="text" name="password" type="password"><br/> <input type="submit" value="提交"> </form>
- 添加全局變量csrf,設置為中間件
在middleware下增加 auth.js
module.exports = (option,app) => { return async function auth(ctx,next){ //添加全局變量 ctx.state.csrf = ctx.csrf; await next(); } }
在 config/config.default.js下調用中間件
config.middleware = ['auth'];
九. Egg中使用cookies
Cookie設置
this.ctx.cookies.set('username','張三',{ maxAge: 1000*3600*24, httpOnly: true, //是否允許在js中獲取 signed: true, // 加簽防止修改 encrypt: true //如果加密的時候獲取時需解密 });
Cookie讀取
this.ctx.cookies.get(‘name’)
Cookie保存對象需要加轉換
十. Egg中使用session
Session的公共配置
config.session ={ maxAge:30*1000*60, renew:true //每次加載重新計算時間 }
Session設置
this.ctx.session.userinfo='hahaha';
Session讀取
this.ctx.session.userinfo
