2017-10-14 21 views
1

私はKoaで簡単なREST APIを構築しようとしています。このために、私はkoa-routerを使用しています。パラメータ付きのPOST要求がkoa-routerで機能しない

  1. 私のようなmainRouter.tsで私のPOSTメソッドにパラメータを追加しようとするたびに、「:idは」ポストマン「は見つからない」と表示私は2つの問題を抱えています。私のリクエスト: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 
}); 
関連する問題