Egg.js 为企业级框架和应用而生,我们希望由 Egg.js 孕育出更多上层框架,帮助开发团队和开发人员降低开发和维护成本。
1 2 3 | $ mkdir egg-example && cd egg-example $ npm init egg --type=simple $ npm i |
1 2 | $ npm run dev $ open http://localhost:7001 |
1 2 3 4 5 6 7 8 9 10 11 | ├── app | ├── router.js │ ├── controller │ | └── home.js │ ├── service │ | └── user.js │ ├── model │ | └── user.js ├── config | ├── plugin.js | └── config.default.js |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | config.mongoose = { url: "mongodb://127.0.0.1/*****", options: {} }; config.cors = { origin: '*', allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH' } config.security = { csrf: { enable: false, }, }; |
1 2 3 4 5 6 7 8 9 10 | module.exports = { mongoose: { enable: true, package: "egg-mongoose" }, cors: { enable: true, package: "egg-cors" } }; |
1 2 3 4 | exports.cors = { enable: true, package: 'egg-cors', } |
[size=1em]router.js
1 2 3 4 5 6 7 | router.get("/api/task", controller.task.index); router.post("/api/task", controller.task.create); router.put("/api/task/:id", controller.task.update); router.delete("/api/task/:id", controller.task.destroy ); // 也可以简写为 router.resources('topics', '/api/task', controller.task); |
controller/task.js[size=1em]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | exports.index = function*() { // ... const result = yield this.service.task.index(this.params); this.body = result; }; exports.create = function*() { // ... const result = yield this.service.task.create(this.request.body); this.body = result; }; exports.update = function*() { // ... const result = yield this.service.task.update(this.params.id, this.request.body); this.body = result; }; exports.destroy = function*() { // ... const result = yield this.service.task.destroy(this.params); this.body = result; }; |
[size=1em]service/task.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | module.exports = app => { class TaskService extends app.Service { *index(params) { let tasks = yield this.ctx.model.Task.find(params); let result = {}; result.data = tasks; return result; } *create(request) { } *update(id, request) { } *destroy(params) { } } return TaskService; }; |
[size=1em]model/task.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | module.exports = app => { const mongoose = app.mongoose; const Schema = mongoose.Schema; const TaskSchema = new Schema({ id: {type: Number}, text: {type: String}, type: {type: String}, progress: {type: Number}, open: {type: Boolean}, start_date: {type: String}, owner_id: [{type: String}], duration: {type: Number}, parent: {type: Number} }); return mongoose.model("Task", TaskSchema); }; |
1 2 3 4 | # 启动服务 npm start # 关闭服务 npm run stop |
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |