ZijianHe / koa-router

Router middleware for koa.
MIT License
4.85k stars 408 forks source link

`param` stops working if followed by `use` #506

Closed divmgl closed 5 years ago

divmgl commented 5 years ago
const http = require('http')
const assert = require('assert')
const request = require('supertest')
const Koa = require('koa')
const KoaRouter = require('koa-router')

const app = new Koa()
const router = new KoaRouter()

router.prefix('/car/:model')

router.param('model', async (model, context, next) => {
  assert(model, 'Model is not provided')
  return await next()
})

router.use(async (context, next) => {
  context.state.reachedThis = true
  return await next()
})

router.get('/', async context => {
  context.body = context.params.model
})

app.use(router.routes(), router.allowedMethods())

request(app.callback())
  .get('/car/tsx')
  .expect(200)
  .then(() => console.log('Passed'))
  .catch(console.error)
AssertionError [ERR_ASSERTION]: Model is not provided
      at router.param (/home/scrapbook/tutorial/app.js:15:3)
      at middleware (/home/scrapbook/tutorial/node_modules/koa-router/lib/layer.js:181:15)
      at dispatch (/home/scrapbook/tutorial/node_modules/koa-router/node_modules/koa-compose/index.js:4
4:32)
      at next (/home/scrapbook/tutorial/node_modules/koa-router/node_modules/koa-compose/index.js:45:18
)
      at /home/scrapbook/tutorial/node_modules/koa-router/lib/router.js:346:16
      at dispatch (/home/scrapbook/tutorial/node_modules/koa-router/node_modules/koa-compose/index.js:4
4:32)
      at /home/scrapbook/tutorial/node_modules/koa-router/node_modules/koa-compose/index.js:36:12
      at dispatch (/home/scrapbook/tutorial/node_modules/koa-router/lib/router.js:351:31)
      at dispatch (/home/scrapbook/tutorial/node_modules/koa-compose/index.js:42:32)
      at /home/scrapbook/tutorial/node_modules/koa-compose/index.js:34:12

Error: expected 200 "OK", got 500 "Internal Server Error"
    at Test._assertStatus (/home/scrapbook/tutorial/node_modules/supertest/lib/test.js:268:12)
    at Test._assertFunction (/home/scrapbook/tutorial/node_modules/supertest/lib/test.js:283:11)
    at Test.assert (/home/scrapbook/tutorial/node_modules/supertest/lib/test.js:173:18)
    at Server.localAssert (/home/scrapbook/tutorial/node_modules/supertest/lib/test.js:131:12)
    at Object.onceWrapper (events.js:273:13)
    at Server.emit (events.js:182:13)
    at emitCloseNT (net.js:1668:8)
    at process._tickCallback (internal/process/next_tick.js:63:19)
fl0w commented 5 years ago

You need to call next

divmgl commented 5 years ago

@fl0w doesn't make a difference, I'll edit the original comment

divmgl commented 5 years ago

This is solved by https://github.com/ZijianHe/koa-router/pull/490