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框架学习笔记的更多相关文章

  1. phalcon(费尔康)框架学习笔记

    phalcon(费尔康)框架学习笔记 http://www.qixing318.com/article/phalcon-framework-to-study-notes.html 目录结构   pha ...

  2. Yii框架学习笔记(二)将html前端模板整合到框架中

    选择Yii 2.0版本框架的7个理由 http://blog.chedushi.com/archives/8988 刚接触Yii谈一下对Yii框架的看法和感受 http://bbs.csdn.net/ ...

  3. JavaSE中Collection集合框架学习笔记(2)——拒绝重复内容的Set和支持队列操作的Queue

    前言:俗话说“金三银四铜五”,不知道我要在这段时间找工作会不会很艰难.不管了,工作三年之后就当给自己放个暑假. 面试当中Collection(集合)是基础重点.我在网上看了几篇讲Collection的 ...

  4. JavaSE中Collection集合框架学习笔记(3)——遍历对象的Iterator和收集对象后的排序

    前言:暑期应该开始了,因为小区对面的小学这两天早上都没有像以往那样一到七八点钟就人声喧闹.车水马龙. 前两篇文章介绍了Collection框架的主要接口和常用类,例如List.Set.Queue,和A ...

  5. JavaSE中Map框架学习笔记

    前言:最近几天都在生病,退烧之后身体虚弱.头疼.在床上躺了几天,什么事情都干不了.接下来这段时间,要好好加快进度才好. 前面用了三篇文章的篇幅学习了Collection框架的相关内容,而Map框架相对 ...

  6. JavaSE中线程与并行API框架学习笔记1——线程是什么?

    前言:虽然工作了三年,但是几乎没有使用到多线程之类的内容.这其实是工作与学习的矛盾.我们在公司上班,很多时候都只是在处理业务代码,很少接触底层技术. 可是你不可能一辈子都写业务代码,而且跳槽之后新单位 ...

  7. JavaSE中线程与并行API框架学习笔记——线程为什么会不安全?

    前言:休整一个多月之后,终于开始投简历了.这段时间休息了一阵子,又病了几天,真正用来复习准备的时间其实并不多.说实话,心里不是非常有底气. 这可能是学生时代遗留的思维惯性--总想着做好万全准备才去做事 ...

  8. scrapy爬虫框架学习笔记(一)

    scrapy爬虫框架学习笔记(一) 1.安装scrapy pip install scrapy 2.新建工程: (1)打开命令行模式 (2)进入要新建工程的目录 (3)运行命令: scrapy sta ...

  9. TensorFlow机器学习框架-学习笔记-001

    # TensorFlow机器学习框架-学习笔记-001 ### 测试TensorFlow环境是否安装完成-----------------------------```import tensorflo ...

  10. spring mvc 及NUI前端框架学习笔记

    spring mvc 及NUI前端框架学习笔记 页面传值 一.同一页面 直接通过$J.getbyName("id").setValue(id); Set值即可 二.跳转页面(bus ...

随机推荐

  1. 改变Jupyter notebook默认浏览器

    1. prompt 输入命令"jupyter notebook --generate-config" 找到jupyter_notebook_config.py所在位置(可能在&qu ...

  2. 记录web面经

    1. npm版本号含义 例如: 2.3.1 (分别表示: 大版本,小版本, 补丁版本)大版本号: 大版本更新,功能添加,向下不兼容.小版本号:功能新增,向下兼容.补丁版本号: 修复bug.~符号含义: ...

  3. 解决mysql使用sql文件不能还原数据库的问题

    来源:https://bbs.sangfor.com.cn/forum.php?mod=viewthread&tid=109605 解决ERROR 1231 (42000): Variable ...

  4. 百题计划-5 codeforces 651 div2 D. Odd-Even Subsequence 二分检查

    https://codeforces.com/contest/1370/problem/D 二分检查 #include<bits/stdc++.h> using namespace std ...

  5. ES得分

    一.概念 1.ES主要用于搜索 2.搜索要把更有相关性的结果展示出来 3.对一个文档评分,相关性越大,评分越高 4.打分的本质是排序 二.评分规则 1.ES5之前,默认评分规则是TF-IDF,这是信息 ...

  6. 【Ubuntu】设置桌面文件夹路径

    Ubuntu 系统会将桌面文件夹路径默认设置为 $HOME/Desktop,包括文档.下载.图片等文件夹路径都有各自的默认路径.若想更改这些文件夹路径,可参考『此链接』. 首先到希望更改的路径下建立桌 ...

  7. Java script Date和长整型互换

    document.write(new Date().getTime()); document.write('<br/>') var date1=new Date(1590024428000 ...

  8. vue element 可编辑表格行内验证

    <template> <div class="page-layout rataMdel"> <el-button type="primary ...

  9. BeanUtils.copyProperties null覆盖问题

    直接用一下工具类 public class CopyUtils { public static String[] getNullPropertyNames (Object source) { fina ...

  10. 时间函数strtotime的强大

    转载:php的strtotime举例-lsstarboy-ChinaUnix博客 1.上周日午夜 strtotime("last sunday"); 2.本周日午夜    strt ...