一.Egg.JS 简介css
Egg.JS是阿里开发的一套node.JS的框架,主要如下几个特色:html
Mode 层对应server文件夹node
View 层 对应view文件npm
Controller 对应 Controller文件夹
4.其余api
提供基于 Egg 定制上层框架的能力,安全
高度可扩展的插件机制cookie
内置多进程管理session
基于 Koa 开发,性能优异app
框架稳定,测试覆盖率高框架
渐进式开发
建立项目
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的目录结构以下
模板地址: 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;
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的封装是为了数据在多个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的引用
新建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 是基于 Koa 实现的,因此 Egg 的中间件形式和 Koa 的中间件形式是同样的,都是基于洋葱圈模型
Egg中间件放置在 app/middleware 目录下的单独文件,它须要 exports 一个普通的 function,接受两个参数:
options: 中间件的配置项,框架会将 app.config[${middlewareName}] 传递进来。
app: 当前应用 Application 的实例。
一、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(); } } };
二、找到config.default.js配置当前项目须要使用的中间件以及中间件的参数
//中间件 config.middleware = ['forbidip']; config.forbidip = { ip: [ '127.0.0.1', '192.168.0.1' ], };
全部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>
在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'];
Cookie设置
this.ctx.cookies.set('username','张三',{ maxAge: 1000*3600*24, httpOnly: true, //是否容许在js中获取 signed: true, // 加签防止修改 encrypt: true //若是加密的时候获取时需解密 });
Cookie读取
this.ctx.cookies.get(‘name’)
Cookie保存对象须要加转换
Session的公共配置
config.session ={ maxAge:30*1000*60, renew:true //每次加载从新计算时间 }
Session设置
this.ctx.session.userinfo='hahaha';
Session读取
this.ctx.session.userinfo