egg笔记(1)

有个业务需求必须写个后端做逻辑处理,大佬告知周围用egg框架的较多,就选这个了!
作为一个前后端分离项目,仅做一个登录逻辑的处理,使用restful API,不涉及前端模版渲染,这篇简单记录下使用。

环境配置

使用简单模式初始化框架,中间选择ts,

1
2
3
mkdir demo && cd demo
npm init egg --type=simple
npm install

跨域设置

安装egg-cors

1
npm install  egg-cors --save

配置plugin.ts

1
2
3
4
5
6
7
8
import { EggPlugin } from 'egg';
const plugin: EggPlugin = {
cors: {
enable: true,
package: 'egg-cors',
}
};
export default plugin;

配置config.default.ts

1
2
3
4
5
6
7
8
9
10
11
config.security = {
csrf: {
enable: false,
},
domainWhiteList: ['*'],//允许访问接口的白名单,例如:http://localhost:8080 *表示均可访问
};
config.cors = {
origin: '*',
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS',
credentials:true//允许前端带cookie
};

附录学习资料
egg官网


egg笔记(1)
https://guoningyan.com/2022/08/10/egg笔记(1)/
作者
Ningyan Guo
发布于
2022年8月10日
许可协议