How to get raw request body in Strapi controller

System Information
  • Strapi Version: 3.6.8
  • Operating System: Mac OS(Big Sur)
  • Database: MySql
  • Node Version: 14.0.0
  • NPM Version: 6.0.0
  • Yarn Version:

Having trouble getting the request body in Strapi contoller. I am trying to send email(provider I am using is SendGrid) after user makes a POST request. Trying to make email dynamic.

Post request body:

{
    name:"testname",
    email:"test@test.com",
    type: "normal"
}

I have a route in \config\routes.json

  {
      "method": "POST",
      "path": "/brochure",
      "handler": "brochure.index",
      "config": {
        "policies": []
      }
  } 

In \controllers\brochure.js

const unparsed = require("koa-body/unparsed.js");


module.exports = {
  index: async (ctx) => {
    const unparsedBody = ctx.request.body[unparsed];

    console.log(unparsedBody); // undefined
     await strapi.plugins["email"].services.email.send({
       to: unparsedBody.email,
       from: "test@asd.com",
       subject: "testing Subject",
       text: `Heloooo ${unparsedBody.name}`,
     });
     ctx.send("Email Sent");
  },
};

In \config\middleware.js I have:

module.exports = {
  settings: {
    cors: {
      enabled: true,
    },
    parser: {
      enabled: true,
      multipart: true,
      includeUnparsed: true,
    },
  },
};

Weird thing is that when I am logging ctx.request.body in terminal logs I can see that the POST object with name, email and type are visible, but when logging, for example, ctx.request.body.name it is undefined.

1 Like

Should be able to extract it like so

const {name, email, type} = ctx.request.body;
3 Likes

For anyone is v4 that encounters this issue, this works:

const body = JSON.parse(ctx.request.body);
const { name } = body;
console.log(name);

When using const unparsed = require("koa-body/unparsed.js");

1 Like

mine ctx.request.body is typed as unknown. this method does not work

Welcome :slight_smile:
I think in TS, if something is typed as unknown you can cast it to something different too :slight_smile:

This works for mi (v4.13.5):

in config/middlewares

export default [
  "strapi::errors",
  "strapi::security",
  "strapi::cors",
  "strapi::poweredBy",
  "strapi::logger",
  "strapi::query",
  {
    name: "strapi::body",
    config: {
      includeUnparsed: true,
    },
  },
  "strapi::session",
  "strapi::favicon",
  "strapi::public",
];

and parse the body

const rawBody = ctx.request.body[Symbol.for("unparsedBody")];