koajs / router

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

Global middleware for 404 overwrites allowed methods response output #157

Open gunnx opened 2 years ago

gunnx commented 2 years ago

Koa version: 2.13.4 @koa/router version: 11.0.1

const Koa = require('koa');
const Router = require('@koa/router');

const app = new Koa();
const router = new Router();

router.get('/', async(ctx, next) => {
  ctx.status = 200;
  ctx.body = ' Hello!'
  await next();
})

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

// catch all to handle non-matched routes
app.use(ctx => {
  ctx.status = 404;
  ctx.body = 'not found'
});

app.listen(3000);

Test 1: Request [GET] http://localhost:3000/ // outputs 'Hello' (200) ✅ Test 2: Request [GET] http://localhost:3000/foo // outputs 'not found' (404) ✅ Test 3: Request [POST] http://localhost:3000/ // outputs 'not found' (405) expected Method not allowed ❌

If I try to log out the ctx.status in the final middleware for Test 3 it always show (404) - I never see the 405 from allowedMethods

widyakumara commented 2 years ago

this one works for me:

koa: 2.13.4 @koa/router: 12.0.0

// ... a bunch of router.get()s;

// catch all for GET
router.get('/(.*)', (ctx) => {
  ctx.status = 404;
  ctx.body = 'Error 404 Not Found';
});

// catch all for all other verbs
router.all('/(.*)', (ctx) => {
  ctx.status = 405;
  ctx.body = 'Error 405 Method Not Allowed';
});

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

app.listen(3000);

hth

fewbadboy commented 4 months ago

the key is use wrong way of next(), you can see #158