egg框架学习笔记
1、安装
npm i egg-init -g
egg-init egg-example --type=simple
cd egg-example
yarn install
npm run dev //localhost:7001
2、多环境配置
config
|- config.default.js
|- config.prod.js
|- config.test.js
|- config.local.js
config.default.js 为默认的配置文件,所有环境都会加载这个配置文件,开发环境config.local.js会覆盖不是合并default配置,测试线上配置同理
配置写法:返回一个对象;写成 exports.key = value 形式;返回一个function
// 将 logger 目录放到代码目录下
const path = require('path');
module.exports = appInfo => {
return {
logger: {
dir: path.join(appInfo.baseDir, 'logs'),
},
};
};
appInfo 说明
pkg package.json
name 应用名,同 pkg.name
baseDir 应用代码的目录
HOME 用户目录,如 admin 账户为 /home/admin
root 应用根目录,只有在 local 和 unittest 环境下为 baseDir,其他都为 HOME。
3、middleware
3.1、exports 一个普通的 function
module.exports = options => {
return async function xxx(ctx,next){
await next();
xxxx
}
}
3.2 使用中间件
在应用中比如config.default.js使用中间件
config.middleware = [ 'authority' ];
在框架或者插件中使用中间件
// app.js
module.exports = app => {
// 在中间件最前面统计请求时间
app.config.coreMiddleware.unshift('report');
};
应用层定义的中间件(app.config.appMiddleware)和框架默认中间件(app.config.coreMiddleware)都会被加载器加载,并挂载到 app.middleware 上。
路由中也可以使用中间件
// app/controller/search.js
exports.index = async ctx => {
ctx.body = `search: ${ctx.query.name}`;
};
// app/middleware/uppercase.js
module.exports = () => {
return async function uppercase(ctx, next) {
ctx.query.name = ctx.query.name && ctx.query.name.toUpperCase();
await next();
};
};
// app/router.js
module.exports = app => {
app.router.get('s', '/search', app.middleware.uppercase(), app.controller.search)
};
4、路由
重定向
//内部重定向
// app/router.js
module.exports = app => {
app.router.get('index', '/home/index', app.controller.home.index);
app.router.redirect('/', '/home/index', 302);
};
// app/controller/home.js
exports.index = async ctx => {
ctx.body = 'hello controller';
};
//外部重定向
// app/router.js
module.exports = app => {
app.router.get('/search', app.controller.search.index);
};
// app/controller/search.js
exports.index = async ctx => {
const type = ctx.query.type;
const q = ctx.query.q || 'nodejs';
if (type === 'bing') {
ctx.redirect(`http://cn.bing.com/search?q=${q}`);
} else {
ctx.redirect(`https://www.google.co.kr/search?q=${q}`);
}
};
5、controller
this.ctx: 当前请求的上下文 Context 对象的实例,通过它我们可以拿到框架封装好的处理当前请求的各种便捷属性和方法。
this.app: 当前应用 Application 对象的实例,通过它我们可以拿到框架提供的全局对象和方法。
this.service:应用定义的 Service,通过它我们可以访问到抽象出的业务层,等价于 this.ctx.service 。
this.config:应用运行时的配置项。
this.logger:logger 对象,上面有四个方法(debug,info,warn,error),分别代表打印四个不同级别的日志,使用方法和效果与 context logger 中介绍的一样,但是通过这个 logger 对象记录的日志,在日志前面会加上打印该日志的文件路径,以便快速定位日志打印位置。
5.1 类的写法
const Controller = require('egg').controller
class PostController extends Controller {
async create (){
const {ctx,service}=this;
let data = await ctx.service.postService.post();
await ctx.render('/index', data);
}
}
5.2 获取 HTTP 请求参数
1、query
在 URL 中 ? 后面的部分是一个 Query String,这一部分经常用于 GET 类型的请求中传递参数。例如 GET /posts?category=egg&language=node 中 category=egg&language=node 就是用户传递过来的参数。我们可以通过 ctx.query 拿到解析过后的这个参数体
2、params
route里面的参数
// app.get('/projects/:projectId/app/:appId', 'app.listApp');
// GET /projects/1/app/2
this.ctx.params.projectId //1
this.ctx.params.appId //2
3、body
ctx.request.query.id 和 ctx.query.id 是等价的,ctx.response.body= 和 ctx.body= 是等价的。
ctx.status === ctx.response.status
ctx.url === ctx.request.url
4、header
ctx.headers,ctx.header,ctx.request.headers,ctx.request.header:这几个方法是等价的,都是获取整个 header 对象。
ctx.get(name),ctx.request.get(name):获取请求 header 中的一个字段的值,如果这个字段不存在,会返回空字符串。
我们建议用 ctx.get(name) 而不是 ctx.headers['name'],因为前者会自动处理大小写。
5、cookie
保存后端header里的set-cookie
if (result.headers['set-cookie']) ctx.set('set-cookie', result.headers['set-cookie']);
自己设置浏览器cookie
如果想要 Cookie 在浏览器端可以被 js 访问并修改:
ctx.cookies.set(key, value, {
httpOnly: false,
signed: false,
});
如果想要 Cookie 在浏览器端不能被修改,不能看到明文:
ctx.cookies.set(key, value, {
httpOnly: true, // 默认就是 true
encrypt: true, // 加密传输
});
6、session
6、Service
处理业务逻辑
// app/service/user.js
const Service = require('egg').Service;
class UserService extends Service {
async find(uid) {
// 假如 我们拿到用户 id 从数据库获取用户详细信息
const user = await this.ctx.db.query('select * from user where uid = ?', uid);
return {
name: user.user_name,
age: user.age
};
}
}
module.exports = UserService;
egg框架学习笔记的更多相关文章
- phalcon(费尔康)框架学习笔记
phalcon(费尔康)框架学习笔记 http://www.qixing318.com/article/phalcon-framework-to-study-notes.html 目录结构 pha ...
- Yii框架学习笔记(二)将html前端模板整合到框架中
选择Yii 2.0版本框架的7个理由 http://blog.chedushi.com/archives/8988 刚接触Yii谈一下对Yii框架的看法和感受 http://bbs.csdn.net/ ...
- JavaSE中Collection集合框架学习笔记(2)——拒绝重复内容的Set和支持队列操作的Queue
前言:俗话说“金三银四铜五”,不知道我要在这段时间找工作会不会很艰难.不管了,工作三年之后就当给自己放个暑假. 面试当中Collection(集合)是基础重点.我在网上看了几篇讲Collection的 ...
- JavaSE中Collection集合框架学习笔记(3)——遍历对象的Iterator和收集对象后的排序
前言:暑期应该开始了,因为小区对面的小学这两天早上都没有像以往那样一到七八点钟就人声喧闹.车水马龙. 前两篇文章介绍了Collection框架的主要接口和常用类,例如List.Set.Queue,和A ...
- JavaSE中Map框架学习笔记
前言:最近几天都在生病,退烧之后身体虚弱.头疼.在床上躺了几天,什么事情都干不了.接下来这段时间,要好好加快进度才好. 前面用了三篇文章的篇幅学习了Collection框架的相关内容,而Map框架相对 ...
- JavaSE中线程与并行API框架学习笔记1——线程是什么?
前言:虽然工作了三年,但是几乎没有使用到多线程之类的内容.这其实是工作与学习的矛盾.我们在公司上班,很多时候都只是在处理业务代码,很少接触底层技术. 可是你不可能一辈子都写业务代码,而且跳槽之后新单位 ...
- JavaSE中线程与并行API框架学习笔记——线程为什么会不安全?
前言:休整一个多月之后,终于开始投简历了.这段时间休息了一阵子,又病了几天,真正用来复习准备的时间其实并不多.说实话,心里不是非常有底气. 这可能是学生时代遗留的思维惯性--总想着做好万全准备才去做事 ...
- scrapy爬虫框架学习笔记(一)
scrapy爬虫框架学习笔记(一) 1.安装scrapy pip install scrapy 2.新建工程: (1)打开命令行模式 (2)进入要新建工程的目录 (3)运行命令: scrapy sta ...
- TensorFlow机器学习框架-学习笔记-001
# TensorFlow机器学习框架-学习笔记-001 ### 测试TensorFlow环境是否安装完成-----------------------------```import tensorflo ...
- spring mvc 及NUI前端框架学习笔记
spring mvc 及NUI前端框架学习笔记 页面传值 一.同一页面 直接通过$J.getbyName("id").setValue(id); Set值即可 二.跳转页面(bus ...
随机推荐
- 前端之Vue day07 混入、插件、elementui、Router、Vuex
一.Props补充 1.父传子在子组件标签上起自定义属性 使用数组 就不演示了,太简单了 2.限制传入的数据类类型 使用对象 同样,展示过的 3.props补充 就是套对象,加以限制 props:{ ...
- start-stop服务器启动
springBoot打成jar包扔到linux服务器 start.sh nohup java -Dfile.encoding=utf-8 -jar XXX-1.0-SNAPSHOT.jar > ...
- 图像高斯滤波的Verilog实现
高斯滤波的原理: 高斯滤波是一种线性平滑滤波,适用于消除高斯噪声,广泛应用于图像处理的减噪过程.通俗的讲,高斯滤波就是对整幅图像进行加权平均的过程,每一个像素点的值,都由其本身和邻域内的其他像素值经过 ...
- jenkins 连接Windows
1.Windows机器需要安装powershell Server 下载路径:https://www.nsoftware.com/powershell/server/ 点击startk开启该服务 2.配 ...
- RepVGG:一个结构重参数化网络
本文来自公众号"AI大道理" ResNet.DenseNet 等复杂的多分支网络可以增强模型的表征能力,使得训练效果更好.但是多分支的结构在推理的时候效率严重不足. 看起来二 ...
- fetch 小分析
includes\database\prefetch.inc line 385 public function fetchField($index = 0) { return $this->fe ...
- 'xxx' must be unique because it is referenced by a foreign key.
'xxx' must be unique because it is referenced by a foreign key. 原因:在绑定外键时,对应的外键字段的没有设置成唯一. 说明:在定义字段时 ...
- goland使用go mod模式
使用go mod之后,想要在goland中有代码提示,有两种方式,一种是使用gopath下的goimport工具,另一种是使用gomod自身的管理工具 我是用的是非gopath的方式,每次新建项目后总 ...
- @JsonSerialize(using = ToStringSerializer.class) 转换失败
解决方案 但实际开发过程中,数据库的bigint,Java的Long都是比较常用的数据类型,为了避免精度丢失,针对这种比较大的数值 全局配置,将数值类型转换为文本如果需要将所有的数值类型全部转换成文本 ...
- 第6课第4节_Binder系统_驱动情景分析_服务注册过程_分析
Service_manager.c 8074 2017/6/30 首先从应用程序分析(Android) binder_loop(bs, svcmgr_handler) { readbuf[0] = B ...