POST 带有参数的请求不适用于 koa-router

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

我正在尝试使用 Koa 构建一个简单的 REST API。为此,我正在使用 koa-router。我有两个问题:

  1. 每当我尝试将参数添加到 mainRouter.ts 中的 POST-Method 时,如“:id”,Postman 会显示 "not found"。我的要求:http://localhost:3000/posttest?id=200

  2. 我无法获取 "ctx.params" 的参数。我在 koajs-page 上也找不到任何相关信息,但我确实到处都能看到这样的例子?!

这是我的应用程序:

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;

如果我将 POST-method 更改为此,则会得到“200”:

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

如果您在请求中使用这样的查询字符串:

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

那么你的路由处理程序应该使用 ctx.query,而不是 ctx.params:

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

您应该只在想要发送这样的请求时使用 ctx.params

http://localhost:3000/posttest/200

在这种情况下,您可以像这样编写路由处理程序:

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