javascriptreactjsfetchkoakoa-router

How to print request body in Koa


I have an app where I need to send data from React frontend to Koa server. Problem is that I have no idea how to print out request body in Koa.

In React I run this code on click

fetch("/metafield", {
      method: "POST",
      body: JSON.stringify({
        key: "key",
        value: "value",
        value_type: "string",
        namespace: "namespace",
      }),
    });

Just a simple fetch with body on Koa server endpoint.

In Koa I have this

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

For some reason this returns empty object {}.

I also tried with

const bodyParser = require("koa-bodyparser");
const server = new Koa();
server.use(bodyParser());

as suggested here, but the output is still the same. After that I tried adding bodyParser to koa-router like

const router = new Router();
router.use(bodyParser());

but still I get empty object in Koa app.

Thanks in advance


Solution

  • Okay. The solution is so simple.

    It worked when I added

    headers: {
            "Content-Type": "application/json",
          },
    

    when sending request with fetch

    Request should look like this now

    fetch("/metafield", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            key: "key",
            value: "value",
            value_type: "string",
            namespace: "namespace",
          }),
        });