0%

eggjs笔记

一、知识

1. session机制

eggjs内置session机制,可设置超时时间等。在超时时间内,session内保存的信息均可以通过同一个cookie获得。

1
2
3
4
this.ctx.session.user_info = {
name: 'test',
age: 10
};

配置超时时间等信息,在/config/config.default.js中添加以下代码

1
2
3
4
5
6
7
exports.session = {
key: 'session_id', // session的名称
maxAge: 10 * 1000, // 有效时间,单位ms
httpOnly: true, // 是否可以js访问
encrypt: true, // 是否加密显示
renew: true // 每次使用是否刷新超时时间
};

2. post请求接收非表单数据

  • post请求在后台可以接收表单数据直接解析成json,但是非表单数据则收不到
  • 需要修改config配置来接收其他类型数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//config.xxx.js
config.bodyParser = {
enable: true,
encoding: 'utf8',
formLimit: '100kb',
jsonLimit: '100kb',
strict: true,
// @see https://github.com/hapijs/qs/blob/master/lib/parse.js#L8 for more options
queryString: {
arrayLimit: 100,
depth: 5,
parameterLimit: 1000,
},
enableTypes: ['json', 'form', 'text'],
extendTypes: {
text: ['text/xml', 'application/xml'],
},
};

二、单测

1. 环境变量

1
2
3
4
5
6
7
8
9
10
11
12
// 默认eggjs的 ctx.app.config.env为prod
// 想要改,需要修改 config/env 文件的值,此值优先级更高,更改环境变量会被此值覆盖

class DataService extends Service {
...
defineModels(models) {
// 使用此方式可以在单测时跳过一些无法执行的流程
if (this.ctx.app.config.env === 'unittest')
return;
}
...
}

2. 分组用例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/* global beforeEach,  describe, it */

'use strict';

const { app, assert } = require('egg-mock/bootstrap');
// const mm = require('egg-mock');
const crypto = require('crypto');
let ctx;

describe('test/service/user.test.js - user', () => {
beforeEach(function () {
// 将ctx mock一下,可以直接使用ctx.service调用service的方法
ctx = app.mockContext();
});
describe('_buildValue', () => {
it('build, only first', async () => {
const name = 'aaa';
const value = await ctx.service.user._buildValue(name, {
first: '1234',
});
const expectValue = {
first: '1234',
};
// 深度强制对比,将两个object做对比
assert.deepStrictEqual(value, expectValue,
`value: ${value} != expectValue ${expectValue}`);
});
});
});

踩坑记

1. csrfToken

  • eggjs内置一个安全机制,需要在请求post时,带上csrf才能通过校验
  • csrf在每次请求都会从cookie中的csrfToken字段中传到前台
  • 在下一次请求中需要在header中设置x-csrf-token字段为对应的值