0

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?

gevorg
  • 4,835
  • 4
  • 35
  • 52
Saad
  • 49,729
  • 21
  • 73
  • 112

2 Answers2

1

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
  • Ah, I see, I had to do `export default router.routes.bind(router)`. And I didn't know about the bind operator as a shorthand for that, thanks a lot for sharing! I hope it makes it into the spec. – Saad Apr 25 '16 at 22:33
0

You have to add a method:

router.allowedMethods()

like this:

app.use(router.routes(), router.allowedMethods())
チーズパン
  • 2,752
  • 8
  • 42
  • 63
fung
  • 1
  • 1