I can't access my request.body object in Koa JS (I am using body parser middleware but still it's not working)

2.5k Views Asked by At

My main server.js File

const koa = require("koa");
const Router = require("koa-router");
const bodyParser = require("koa-bodyparser");

const app = new koa();
var router = new Router();

// app.use(bodyParser({ enableTypes: ["json", "text"] }));
// I have also tried passing enabletypes parameteres but it still is not working..
 
app.use(bodyParser());
app.use(router.routes());
app.use(router.allowedMethods());

router.post("/", async (ctx) => {
  console.log(ctx);

});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server started on port no ${PORT}`));

When i hit this router.post("/") end point ... just for the purpose to see my context object i console logged the context object and it shows the following in the console when I hit this endpoint using postman (i am send JSON body in the request)

enter image description here

My postman request

enter image description here

How do I access my body (JSON object) ?

2

There are 2 best solutions below

2
Sebastian Hildebrandt On

To access your body object, try the following:

const body = ctx.request.body;

Secondly: because in one of the comments there was a note, why you get a 404. I guess this is because in your route you are not returning anything. So your route could look like:

router.post("/", async (ctx) => {
  const body = ctx.request.body;
  console.log(body);

  return (true)                   // or whatever you want to return to the client
});
0
codeMonkeyHopeful On

I'd suggest using something to return i.e. if you return nothing you are going to get a 404 with Koa. Just set the body of the ctx i.e. ctx.body="something here".

Other than that depending on what you are using in the app to hit it Postman may work slightly different and pass additional headers etc. I've run into this a handful of times using Thunder Client on VS Code where it works when poking it but in the app something is slightly off. I've ONLY run into this with Koa and never express so might be worth checking and logging along the way WITHIN the app.