一、生成项目&启动
npm init egg --type=simple
启动&访问
$ npm run dev
$ open http://localhost:7001
二、MVC
-
view 视图 模板 页面的展示
-
Controller 负责处理一些业务逻辑
-
model 模型(service) 和数据打交道(查询数据库、操作数据库数据、请求数据)(复杂的业务逻辑,以及数据操作)
三、vscode小技巧
安装eggjs插件,新建js文件后可快速创建文件(controller, service, )
四、获取get、post传值
// get
this.ctx.query
// get-动态传值
this.ctx.params
// post
this.ctx.request.body
五、全局变量
在中间件中设置全局变量
语法:ctx.state.token = '123'
完整版
@file(auth)
module.exports = (option, app) => {
return async function auth(ctx, next) {
// 设置模板全局变量
ctx.state.csrf = ctx.csrf;
await next();
}
}
注意:要在config.default中挂载config.middleware = ['auth'];