Karl Morrison Karl Morrison - 2 months ago 20
Node.js Question

Koa-router issue with / and /signin

/index.js:

//... code
import routes from './routes/bind';
app.use(routes.routes(), routes.allowedMethods());
//... code


/routes/bind.js:

'use strict';

import KoaRouter from 'koa-router';
const router = new KoaRouter();

// routes requests
import routes from './routes';
router.use(`/`, routes.routes(), routes.allowedMethods());

export default router;


/routes/routes.js:

'use strict';

import KoaRouter from 'koa-router';
const router = new KoaRouter();

// home page
router.get(`/`, async function(ctx, next) {
ctx.body = 'home page';
});

// sign in page
router.get(`/signin`, async function(ctx, next) {
ctx.body = 'sign in page';
});

export default router;


127.0.0.1:3000
works (displays home page)

127.0.0.1:3000/signin
does not work (displays 404)

127.0.0.1:3000/signin
isn't working for some reason. Any ideas?

Answer

Currently 127.0.0.1:3000//signin shows the sign in page. So remove the preceding / from the route definition.

The reason why 127.0.0.1:3000 works correctly is that koa-router can automatically handle trailing slashes. For the home page, the route you're actually defining is //, but koa-router can handle this. However, for the sign in page the route is //signin, but koa-router can't (nor should it) handle preceding slashes.

Comments