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. Python 堆、栈和队列详解

    队列: 1.队列是一种特殊的线性表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的线性表.进行插入操作的端称为队尾,进 ...

  2. 2023-03-01 Error: Invalid hook call.Hooks can only be called inside of the body of a function component.

    问题描述:rn项目使用钩子useState,详细报错如下: Error: Invalid hook call. Hooks can only be called inside of the body ...

  3. WPF美化常用(渐变)

    1,线性渐变色设置 2,径向渐变色设置(圆形)

  4. eval()

    s='12*2'd=eval(s)#字符串运算函数print(d) 结果: 24

  5. cgroup和Linux Namespace基础操作

    一.开头 接触过docker的同学多多少少听过这样一句话"docker容器通过linux namespace.cgroup特性实现资源的隔离与限制".今天我们来尝试学习一下这两个东 ...

  6. a菜单点击标红,其他标黑代码

    <script> let aList = document.querySelectorAll('a'); console.log(aList); for (let index = 0; i ...

  7. 浅谈组件二封-vue

    目录 组件二封不是换一种写法 组件二封应当具备哪些条件 我认为的二封应当有哪些作用 二封的好处 先来一个列表页demo来看看效果(Vue2) 本文仅仅针对vue系列做探讨, 项目倾向于大量增删改查的后 ...

  8. YOLOV4网络

    Yolov4网络代码 from collections import OrderedDict import torch import torch.nn as nn from Darknet_53 im ...

  9. easypoi多sheet导出

    以前一直接触的是单sheet导出,这次的需求换成了多sheet导出,算是一个难点所以得记录一下 底层关键的代码就是: private static void defaultExport(List< ...

  10. Jmeter - Config Tips

    Guideline: Jmeter.properties file should avoid to be modified , modified user.properties instead > ...