I want to read ctx.request.body
from a post without body-parser middleware.
const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
app.use(router.routes());
router.post('/publish', async (ctx, next) => {
let msg = JSON.stringify(ctx.request.body);
console.log(msg); //undefined
console.log(ctx.request.body); //undefined
console.log(ctx.req.body); //undefined
});
app.listen(process.env.PORT);
Using curl -X POST -H "Content-Type: application/json" -d '{"key":"val"}' 'http://localhost:8080/publish'
I get 3 undefined.
How do I solve this problem? I know that koa can't parse req.body
, but why doesn't JSON.stringify(ctx.request.body)
work?
JSON.stringify(ctx.request.body)
does not work, because it only gets set if you use one of the available body parsers. So if you do not want to use body-parser (or any other body-parser middleware), you have to parse the body fromreq.body
by yourself.But honestly, why would you not want to use one of the existing solutions for your problem?