koa-better-router
koa-better-router copied to clipboard
notFound option does not respect router prefix
notFound
option does not respect router prefix.
It is called for any non-matched path, regardless of the prefix, meaning it can't be used if there are several routers under different prefixes.
Example:
const Koa = require('koa')
const Router = require('koa-better-router')
const router1 = new Router({
prefix: '/api/v1',
notFound: (ctx, next) => {
ctx.status = 404
next()
}
})
router1.addRoute('GET /foo', ctx => {
ctx.body = 'foo1'
})
const router2 = new Router({prefix: '/api/v2'})
router2.addRoute('GET /foo', ctx => {
ctx.body = 'foo2'
})
const app = new Koa()
app.use(router1.middleware())
app.use(router2.middleware())
app.listen(3000)
Then call it:
$ curl localhost:3000/api/v2/foo -v
> GET /api/v2/foo HTTP/1.1
> Host: localhost:3000
> User-Agent: curl/7.54.0
> Accept: */*
>
< HTTP/1.1 404 Not Found
< Content-Type: text/plain; charset=utf-8
< Content-Length: 4
< Date: Thu, 03 Aug 2017 06:33:21 GMT
< Connection: keep-alive
<
foo2
Expected reply: HTTP 200 OK.
Funnily enough, if I use an async handler for v1's notFound
, the behaviour changes and it doesn't even reach the v2 handler:
// ...
notFound: async ctx => {
ctx.status = 404
ctx.body = {error: 404}
}
Response:
$ curl localhost:3000/api/v2/foo -v
...
< HTTP/1.1 404 Not Found
< Content-Type: application/json; charset=utf-8
< Content-Length: 13
< Date: Thu, 03 Aug 2017 07:55:35 GMT
< Connection: keep-alive
<
{"error":404}
(I set body here to distinguish between Koa's default 404 and notFound handler - but it's not what triggers the problem).
So, alas, it's all broken in different ways.