meh_programmer meh_programmer - 5 months ago 32
Node.js Question

Exporting routes in Koa

I'm having a strange issue when exporting my routes. For some reason, this code works for me:

app.js

import Koa from 'koa'
import routes from './routes/index'

const app = new Koa()

app.use(routes)

app.listen(3000, () => {
console.log('Server listening at http://localhost:3000')
})

export default app


routes/index.js

import Router from 'koa-router'
const router = new Router()

router.get('/', async ctx => {
await ctx.render('index')
})

export default router.routes()





but when I just export the routes function and then try to call it in
app.js
, I get an error:

app.js

import Koa from 'koa'
import routes from './routes/index'

const app = new Koa()

app.use(routes())

app.listen(3000, () => {
console.log('Server listening at http://localhost:3000')
})

export default app


routes/index.js

import Router from 'koa-router'
const router = new Router()

router.get('/', async ctx => {
await ctx.render('index')
})

export default router.routes


Why doesn't it work when I do it the second way?

Answer

You probably would like to export a bound function, so this inside it would refer to a router object.

It could be done nicely with a bind operator. I believe it's already available since you are using async/await.

import Router from 'koa-router'
const router = new Router()

router.get('/', async ctx => {
  await ctx.render('index')
})

export default ::router.routes
Comments