How do I separate routes with trie-route for koajs?
app.js:
const Koa = require('koa')
const get = require('./routes/get')
const post = require('./routes/post')
const app = new Koa()
app.use(get)
app.use(post)
app.listen(3000)
routes/get.js:
'use strict'
const Router = require('koa-trie-router')
const router = new Router()
// middleware that is specific to this router
router.use(async (ctx, next) => {
console.log('Time: ', Date.now())
await next()
})
// define the home page route
router.get('/', async (ctx, next) => {
ctx.type = 'json'
ctx.body = {
message: 'Birds home page'
}
})
// Separate this post route in a new file.
// router.post('/', async (ctx, next) => {
// ctx.type = 'json'
// ctx.body = {
// message: 'Post birds home page'
// }
// })
module.exports = router.middleware()
routes/post.js:
'use strict'
const Router = require('koa-trie-router')
const router = new Router()
router.post('/', async (ctx, next) => {
ctx.type = 'json'
ctx.body = {
message: 'Post birds home page'
}
})
module.exports = router.middleware()
When I try to post it on my Postman at http://127.0.1.1:3000/
:
Method Not Allowed
Any ideas how can I get around to this?
My package.js:
{
"name": "basic",
"version": "1.0.0",
"description": "basic sample",
"main": "app.js",
"author": "xxx",
"license": "BSD-2-Clause",
"dependencies": {
"koa": "^2.3.0",
"koa-trie-router": "^2.1.5"
},
"keywords": [
"kao",
"nodejs"
]
}
The problem you're seeing is due to the first call to app.use()
taking precedence over the next one. For example, if I do the following instead:
app.use(post)
app.use(get)
Then I get the same error but on the GET
request. To get this to work, what I did was to return the actual router from routes/get.js
and routes/post.js
, and then configure the middleware in app.js
.
So in your routes/get.js
and routes/post.js
-
Instead of:
module.exports = router.middleware()
Export:
module.exports = router
In app.js
:
const Koa = require('koa')
const get = require('./routes/get')
const post = require('./routes/post')
const Router = require('koa-trie-router')
const router = new Router()
router.get(get.middleware());
router.post(post.middleware());
const app = new Koa()
app.use(router.middleware());
app.listen(3000)