koajs / router

Router middleware for Koa. Maintained by @forwardemail and @ladjs.
MIT License
871 stars 176 forks source link

Router .all throws 404 #97

Closed artecoop closed 3 years ago

artecoop commented 4 years ago

Hello! (Pay attention: typescript ahead!) I have a simple server in Koa and I just updated router to it's latest version and naming convention (from koa-router": "8.0.8").

"koa": "2.13.0",
"koa-body": "4.2.0",
"@koa/router": "9.3.1",
"@koa/cors": "3.1.0",
"koa-static": "5.0.0",

Before any route is resolved, I need to check if the context's request has a token. If so, I transform the token to an object and pass it back in the context's state:

import { Context, Next } from 'koa';
import * as Router from '@koa/router';

const auth = new Router();

auth.all(/^\/api\/(.*)(?:\/|$)/, (ctx: Context, next: Next) => {
    const token = ctx.request.headers['authorization'];
    try {
        ctx.state.user = myAwesomeTokenParser(token);
        next();
    } catch (e) {
        ctx.throw(e.statusCode, e.message);
    }
});

export default auth;

the entry point for the Koa server is

import * as koa from 'koa';

const SERVER = new koa();

SERVER.use(public.routes())

SERVER.use(auth.routes())

SERVER.use(hidden.routes())

SERVER.listen(9999);

Because ordering matters in koa router, all the routes defined after the SERVER.use(auth.routes()) are parsed after auth.all(...). Note that public routes are unaffected.

Now the problem is that after the upgrade, every "hidden" route throws 404. Debugging my server show me that hit the auth.all correctly, but the next() seems to throw the request into the void.

Any clue on my error?

winkies commented 3 years ago

Hello !

By now, I hope you figured it out.

But if not and regarding your use case, I will take a look to koa-jwt, a middleware for validating JSON Web Tokens.

It should work with @koa/router.

dominicegginton commented 3 years ago

I believe this issue can be closed as the resolution was given by @niftylettuce over on #101