2017-10-14 73 views
1

我正在尝试用Koa构建一个简单的REST API。为此,我正在使用koa-router。我有两个问题:带参数的POST请求不支持koa-router

  1. 每当我尝试参数一样mainRouter.ts添加到我的后法“:ID”,邮差显示“未找到”。我的要求:http://localhost:3000/posttest?id=200

  2. 我无法获得带有“ctx.params”的参数。我在koajs页面上也找不到任何关于它的内容,但我确实在这里看到了像这样的例子?!

这是我的应用程序:

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方法来此,然后我得到“200”:

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

回答

0

如果您使用的是查询字符串您的要求是这样的:

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 
}); 
相关问题