如何使用 koajs 的 trie-route 分离路由?

How to separate routes with trie-route for koajs?

如何为 koajs 使用 trie-route 分隔路由?

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()

当我在 http://127.0.1.1:3000/ 上尝试 post 它时:

Method Not Allowed

有什么办法解决这个问题吗?

我的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"
  ]
}

您遇到的问题是由于对 app.use() 的第一次调用优先于下一次调用。例如,如果我改为执行以下操作:

app.use(post)
app.use(get)

然后我得到了同样的错误,但是在 GET 请求上。为了让它工作,我所做的是 return 来自 routes/get.jsroutes/post.js 的实际路由器,然后在 app.js.

中配置中间件

所以在你的 routes/get.jsroutes/post.js -

而不是:

module.exports = router.middleware()

导出:

module.exports = router

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)