在看這個之前還是需要先看文檔:
https://eggjs.org/zh-cn/basics/router.html
https://eggjs.org/zh-cn/basics/controller.html
這裏我所做的也就是一個文檔的搬運工再根據自己的需求整理了一下而已。
在之前的Node.js系列博客中都是用的Express,這次使用Egg.js之後明顯感覺簡潔多了。
GET請求
參數獲取方式一:
'use strict';
const Controller = require('egg').Controller;
class HomeController extends Controller {
async query() {
const { ctx } = this;
ctx.body = {
query: ctx.query,
id: ctx.query.id,
data: ctx.query.data
}
// http://localhost:7001/query?id=2&data=aa
// {
// "query": {
// "id": "2",
// "data": "aa"
// },
// "id": "2",
// "data": "aa"
// }
}
}
module.exports = HomeController;
路由:
'use strict';
/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const { router, controller } = app;
router.get('/query', controller.home.query);
};
參數獲取方式二:
async params() {
const { ctx } = this;
ctx.body = {
params: ctx.params,
id: ctx.params.id,
data: ctx.params.data
}
// http://localhost:7001/params/2/aa
// {
// "params": {
// "id": "2",
// "data": "aa"
// },
// "id": "2",
// "data": "aa"
// }
};
router.get('/params/:id/:data', controller.home.params);
POST請求
async post() {
const { ctx } = this;
ctx.body = {
post: ctx.request.body,
id: ctx.request.body.id,
data: ctx.request.body.data
}
// http://localhost:7001/post
// {
// "post": {
// "id": "2",
// "data": "aa"
// },
// "id": "2",
// "data": "aa"
// }
};
router.post('/post', controller.home.post);
這裏的GET和POST請求其實沒什麼,主要是要注意下和Express的差異。總體感覺就是使用真的簡單。