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?

4

2 回答 2

1

你可能想导出一个绑定函数,所以this它里面会引用一个路由器对象。

使用绑定运算符可以很好地完成它。我相信它已经可用,因为您正在使用async/await.

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

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

export default ::router.routes
于 2016-04-24T21:15:14.567 回答
0

您必须添加一个方法:

router.allowedMethods()

像这样:

app.use(router.routes(), router.allowedMethods())
于 2016-04-25T09:07:58.207 回答