get
xx.com/xx='xxx'&xx=xx
获取方式 this.ctx.query
post 默认需要csrf配置
post请求 默认会提示csrf攻击没有设置 invalid csrf token 添加csrf
get方式渲染ejs两种方式
1.普通方式 直接把csrf设为参数传递过去
await this.ctx.render('postsub',{csrf:this.ctx.csrf})
2.使用中间件避免每次都要配置
await this.ctx.render('postsub');
中间件auth.js
配置中间件 config.default.js
config.middleware = ['auth'];
定义使用中间件
module.exports=(options,app)=>{
return async(ctx,next)=>{
// state设置全局变量 调用方式 ctx.state.csrf
ctx.state.csrf=ctx.csrf;
await next();
}
}
ejs 直接可加载静态资源 无需配置 ../public/xxx
1.将csrf显示再地址栏中
<form action="/doAdd?_csrf=<%=csrf%> " method="POST">
用户名: <input type="text" name="username" /> <br><br>
密 码: <input type="text" name="password" type="password" />
<button type="submit">提交</button>
</form>
2.把csrf 从地址中隐藏掉
<form action="/doAdd?" method="POST">
<input type="hidden" name='_csrf' value="<%=csrf%>">
用户名: <input type="text" name="username" /> <br><br>
密 码: <input type="text" name="password" type="password" />
<button type="submit">提交</button>
</form>
配置ejs模板引擎
npm i egg-view-ejs
plugin.js
exports.ejs = {
enable: true,
package: 'egg-view-ejs',
};
config.defalut.js
// 配置第三方模块 使用config
config.view = {
mapping: {
'.html': 'ejs',
},
};
html中通过ejs获取 使用的模板引擎是:<%=view.mapping['.html']%> 使用view调用的原因是直接导出 exports
js中获取配置中文件 this.config.xxx (看官方文档)
获取post请求的数据
this.ctx.request.body
mvc
1.service news.js 获取数据或者数据库读取数据
module.exports = app => {
class NewsService extends app.Service {
async getData(){
let data='我是新闻哈哈哈';
let list = ['11111', '2222', '3333'];
let view=this.config.view;
return{
data,
list,
view
}
}
}
return NewsService
}
2. controller news.js处理数据渲染到ejs
'use strict';
const Controller = require('egg').Controller;
class HomeController extends Controller {
async index() {
const { ctx } = this;
let msg=(await this.service.news.getData()).data;
ctx.body = 'hi, egg'+msg;
}
}
module.exports = HomeController;
3.html xx.html
然后通过view xx.html 中渲染msg