# egg.js 快速开始
# 1. 介绍
说明:
- 为企业级框架和应用而生的 node.js 框架
- 约定优于配置
特点:
- 基于 Koa
与其他框架的对比:
# 2. 创建项目
快速生成项目:
mkdir egg-example
cd egg-example
npm init egg --type=simple
npm i
# ? Please select a boilerplate type simple - Simple egg app boilerplate
启动项目:
# 修改源码后,自动“重启”
npm run dev
open http://localhost:7001
# 3. hello world
目录:
egg-example/
app/controller/home.js
app/router.js
新增路由:
app/controller/home.js
const { Controller } = require('egg'); module.exports = class HomeController extends Controller { // ... async test() { const { ctx } = this; ctx.body = '<h1>hello, test</h1>'; } }
app/router.js
module.exports = app => { const { router, controller } = app; // ... router.get('/test', controller.home.test); };
npm scripts:
{
"scripts": {
// 启动(服务/后台)
"start": "egg-scripts start --daemon --title=egg-server-example",
// 停止
"stop": "egg-scripts stop --title=egg-server-example",
// 启动(开发模式)
"dev": "egg-bin dev",
},
}
# 4. GET 请求
query string:
/* 请求 */
// http://127.0.0.1:7001/test/get/query-string?name=张三&age=18
/* router.js */
router.get('/test/get/query-string', controller.testRequest.testGetQueryString);
/* test-request.js */
async testGetQueryString() {
const { ctx } = this;
console.log('ctx.query', ctx.query);
// ctx.query { name: '张三', age: '18' }
ctx.body = 'testGetQueryString';
}
path params:
/* 请求 */
// http://127.0.0.1:7001/test/get/path-params/李四 # 404
// http://127.0.0.1:7001/test/get/path-params/李四/19
/* router.js */
router.get('/test/get/path-params/:name/:age', controller.testRequest.testGetPathParams);
/* test-request.js */
async testGetPathParams() {
const { ctx } = this;
console.log('ctx.params', ctx.params);
// ctx.params { name: '李四', age: '19' }
ctx.body = 'testGetPathParams';
}
# 5. POST 请求
关闭 CSRF (验证 Referer 请求头):
// config/config.default.js
config.security = {
csrf: {
enable: false,
},
};
test.http:
POST http://127.0.0.1:7001/test/post
Content-Type: application/json
{
"name": "王五",
"age": 21
}
示例:
/* router.js */
router.post('/test/post', controller.testRequest.testPost);
/* test-request.js */
async testPost() {
const { ctx } = this;
console.log('ctx.request.body', ctx.request.body);
// ctx.request.body { name: '王五', age: 21 }
ctx.body = 'testPost' + ctx.request.body;
}
# 6. service
目录:
egg-example/
app/controller/test-service.js
app/service/person.js
app/router.js
app/controller/test-service.js:
const { Controller } = require('egg');
module.exports = class TestServiceController extends Controller {
async test() {
const { ctx } = this;
const personService = this.ctx.service.person;
ctx.body = await personService.getPerson(123);
}
};
app/service/person.js:
const Service = require('egg').Service;
module.exports = class PersonService extends Service {
async getPerson(id) {
return { id, name: '小红', age: 18 };
}
};
app/router.js:
module.exports = (app) => {
const { router, controller } = app;
router.get('/test/service', controller.testService.test);
};
上一篇: 下一篇:
本章目录