-
Notifications
You must be signed in to change notification settings - Fork 13
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Separate routes into files? #38
Comments
try 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())
return next() // <-- here
}) Also you can use koa-architect that makes same things. |
@nervgh still the same after adding that. |
I understand that. You have to use one router per namespace (or use koa-mount to separation of paths): app.js const Koa = require('koa')
const middleware = require('./routes/index')
const app = new Koa()
app.use(middleware) // get & post
app.listen(3000) routes/index.js 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() Or you could just export functions if you want to store get & post handlers in the separate files: const Koa = require('koa')
const middleware = require('./routes/index')
const app = new Koa()
app.use(middleware) // get & post (one router)
app.listen(3000) routes/index.js const Router = require('koa-trie-router')
const getMiddleware = require('./routes/middleware/get')
const postMiddleware = require('./routes/middleware/get')
const router = new Router()
// define the home page route
router.get('/', getMiddleware)
// Separate this post route in a new file.
router.post('/', postMiddleware)
module.exports = router.middleware() routes/middleware/get.js module.exports = async (ctx, next) => {
ctx.type = 'json'
ctx.body = {
message: 'Birds home page'
}
} routes/middleware/post.js module.exports = async (ctx, next) => {
ctx.type = 'json'
ctx.body = {
message: 'Birds home page'
}
} |
@lautiamkok please, close this issue when it is solved. |
How do I separate routes into files?
app.js:
routes/get.js:
routes/post.js:
When I try to post it on my Postman at
http://127.0.1.1:3000/
:Any ideas how can I get around to this?
The text was updated successfully, but these errors were encountered: