前言
這一篇將會繞回前面講一下 router 的部分,這一篇其實前面就應該講了,但是紀錄的太順結果就忘了QQ
route 模組化
由於前面已經安裝過 koa-router
所以這邊就不再次講如何安裝的過程,如果不清楚就看 這一篇
首先我們先建立一個 route 資料夾,並在底下建立一隻檔案叫 index.js
![Image]()
內容當然要引入相關的套件並模組化,但是 koa 這邊與 express 的寫法有點不同,並將 app.js
的 route
拆出來放到 route/index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| const router = require('koa-router')();
router.get('/',async (ctx, next) => { ctx.cookies.set('cid','1234', cookieSet); await ctx.render('index', { title: 'EJS !' }); });
router.post('/post', async (ctx, next) => { ctx.session.email = ctx.request.body.email; ctx.session.name = ctx.request.body.name; ctx.redirect('/'); });
module.exports = router
|
另外這部分還可以簡寫變成這樣
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| const router = require('koa-router')();
router .get('/',async (ctx, next) => { ctx.cookies.set('cid','1234', cookieSet); await ctx.render('index', { title: 'EJS !' }); }) .post('/post', async (ctx, next) => { ctx.session.email = ctx.request.body.email; ctx.session.name = ctx.request.body.name; ctx.redirect('/'); })
module.exports = router
|
接下來 app.js
的部分就是引入 route 並使用,所以程式碼如下
1 2
| const indexRoute = require('./route/index'); app.use(indexRoute.routes(), indexRoute.allowedMethods());
|
接下來就可以執行 koa 來看看是否正常~
![執行狀況]()