Ctx.request.body ist empty when receiving GET request with payload

System Information
  • Strapi Version: 3.0.6
  • Operating System: Linux (debian based)
  • Database: Postgres
  • Node Version: 16.13.0
  • NPM Version:
  • Yarn Version:

Hi, maybe this is an easy question, but it was not possible for me to find a satisfying solution:

  • there is a GET-request sent to an object in strapi (finance-suggestions)
  • this request contains payload the body
  • the tag “content-length” contains the correct size of the payload
    But: Accessing this content is not possible. There is no “undefined” error thrown, but the object is just empty when putting it to console for example:

Lines of code:

module.exports =
	findAction: async(ctx) =>
		let traceid	= loghandler.createTraceID();
				throw "Invalid method";
			loghandler.logInformation(traceid, "Received new finance-suggestion GET request.");
			loghandler.logInformation(traceid, "Request header content: " + JSON.stringify(ctx.request.header));
			loghandler.logInformation(traceid, "Request body content: " + JSON.stringify(ctx.request.body));

Thanks to an idea posted in stackoverflow (thanks to user “shriek” here: node.js - How to access "request payload" in Koa web-framework? - Stack Overflow), I found a solution how to read out the payload of a message within the raw content of the request.

First add a async function to your controller code, which handles the asynchronous readout from the raw request:

async function getBody(rawrequest) {
  let semaphore = new Promise((resolve, reject) => {
      let bodycontent = '';
      rawrequest.on('data', datapart => { bodycontent += datapart; } );
      rawrequest.on('end', () => { resolve(JSON.parse(bodycontent)); } );
      rawrequest.on('error', () => { reject("Error") });
  return semaphore;

The important part here is, that a semaphore (in shape of a new created promise) will handle the runtime state of the true readout.
Now the second part is to implement the call of this new created function there where the ctx - object is located while runtime:

await getBody(ctx.req)
        .then( ( bodydata ) => {  console.log(bodydata) } )
        .catch( (error) => { console.log("There was an error reading out the body" + error) } )

It is further needed to impement a better error handling. In the case of sending empty or no body or a non-json one, the call of JSON.parse() will fail. But in all, with the code above it is possible to read out the raw content of the body. Hope it helps you and that the code written is human-readable.