Koa: How to get POST params?

Created on 28 Apr 2016  路  7Comments  路  Source: koajs/koa

koa: v2.0.0
koa-router: v7.0.1

// user
router
.get('/user/:id', async (ctx, next) => {
    let user = await User.query();
    ctx.body = user;
}) 
.post('/user/', async (ctx, next) => {
    ctx.body = ctx.req;
 })

Everything seems all right, but I can't find the post params.

Insert the code:

.get('/user/:id', async (ctx, next) => {
    let user = await User.query();
    ctx.body = user;
})
.post('/user/', async (ctx, next) => {
    var data = '';
    ctx.on('data', function (chunk) {
        data += chunk;
    })
    ctx.on('end', function (chunk) {
        console.log(data);
    })
    ctx.body = ctx.req;
})

The data will be print correctly!
I don't want to use this approach.
Have any good Suggestions?

Most helpful comment

@xunjianxiang you can get your POST params like this:

ctx.request.body // your POST params
ctx.params // URL params, like :id

All 7 comments

@xunjianxiang you can get your POST params like this:

ctx.request.body // your POST params
ctx.params // URL params, like :id

I get ctx.request.body but it's undefined

@hanxu317317 you need a body parser. Google for koa-bodyparser and/or koa-body.

thank you, it's ok

yeah

yes

Hi, does body parser required some extra config, I still get an empty array using both ctx.request.body and ctx.params. Im also using koa-joi-router. I want to access the verification code from params.

thx!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ElegantScripting picture ElegantScripting  路  5Comments

tracker1 picture tracker1  路  3Comments

koalex picture koalex  路  3Comments

rainesinternationaldev picture rainesinternationaldev  路  5Comments

xinshouke picture xinshouke  路  4Comments