Search code examples
http-posturl-parameterskoakoa-router

POST request with parameters doesn't work with koa-router


I'm trying to build a simple REST API with Koa. For this, I am using koa-router. I have two problems:

  1. Whenever I try to add parameters to my POST-Method in mainRouter.ts like ":id", Postman shows a "not found". My request: http://localhost:3000/posttest?id=200

  2. I cannot get the parameters with "ctx.params". I also can't find anything about it on the koajs-page, but I do see examples like this everywhere?!

This is my app:

app.ts

import * as Koa from 'koa';
import * as mainRouter from './routing/mainRouter';
const app: Koa = new Koa();
app
    .use(mainRouter.routes())
    .use(mainRouter.allowedMethods());
app.listen(3000);

mainRouter.ts

import * as Router from 'koa-router';

const router: Router = new Router();
router
    .get('/', async (ctx, next) => {
        ctx.body = 'hello world';
    });
router
    .post('/posttest/:id', async (ctx, next) => {
        ctx.body = ctx.params.id;
    });
export = router;

If I change the POST-method to this, then I get "200":

router
    .post('/posttest', async (ctx, next) => {
        ctx.body = ctx.query.id;
    });

Solution

  • If you're using a query string in your request like this:

    http://localhost:3000/posttest?id=200
    

    Then your route handler should be using ctx.query, not ctx.params:

    router.post('/posttest', async (ctx, next) => {
      console.log(ctx.query.id); // 200
    });
    

    You should only use ctx.params when you want to send requests like this:

    http://localhost:3000/posttest/200
    

    In which case you would write the route handler like so:

    router.post('/posttest/:id', async (ctx, next) => {
      console.log(ctx.params.id); // 200 
    });