Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Global middleware for 404 overwrites allowed methods response output #157

Open
gunnx opened this issue Jul 4, 2022 · 2 comments
Open

Global middleware for 404 overwrites allowed methods response output #157

gunnx opened this issue Jul 4, 2022 · 2 comments

Comments

@gunnx
Copy link

gunnx commented Jul 4, 2022

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
Copy link

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
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants