Search code examples
jsonwordpresswordpress-rest-api

Custom WP API endpoint NULL body data


I have a weird issue, that bashes my head in. It's probably something minor that I am overlooking, but for the life of me I cannot figure it out.

Here's the premise:

  • I am making a POST request to a custom registered api endpoint in a wp environment, to which i am sending json data from a form. Content type is set correctly and if i debug by dumping $request->get_body() it shows the correct data that i've passed on.
  • however, i also send base64 encoded image data, resulted from a file reader. If i add another item to the data being send and the base64 string as the value for it, the dump becomes NULL. Taking the base64 string out of the json, makes the dump become ok again.

I have also tried to increase the max upload size, and post size however, since the file i am using as test is 20 KB, I do not think this is the issue.

I am hoping somebody can help me see the error of my ways.

Here's a code snippet. Note that the URL is not real here, but real in my environment. Also, due to char limit, I could not post the whole base64 image in the snippet, but rest assured it is correct. I even tried with a 1px by 1px transparent image and I had the same problem.

var image = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4QDeRXhpZgAASUkqAAgAAAAGABIBAwABAAAAAQAAABoBBQABAAAAVgAAABsBBQABAAAAXgAAACgBAwABAAAAAgAAABMCAwABAAAAAQAAAGmHBAABAAAAZgAAAAAAAAA4YwAA6AMAADhjAADoAwAABwAAkAcABAAAADAyMTABkQcABAAAAAECAwCGkgcAFgAAAMAAAAAAoAcABAAAADAxMDABoAMAAQAAAP//AAACoAQAAQAAABgCAAADoAQAAQAAAGIBAAAAAAAA...";

var data = {
    'test': 'hello world',
    'image': image
};

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify(data);

var requestOptions = {
    method: 'POST',
    headers: myHeaders,
    body: raw,
    redirect: 'follow'
};

fetch("/wp-json/test/v1/testapi", requestOptions)
    .then(response => response.text())
    .then(result => console.log(result))
    .catch(error => console.log('error', error));

Solution

  • I have solved the issue. It was unrelated to json / javascript / api. It was a simple issue of tmp folder ownership. Since there were no errors spewing out by the php managing the request, I never noticed a PHP NOTICE saying to check permissions in temp folder as php was unable to upload the temp file there. And indeed, while the permissions were fine, the group ownership was not.

    Sorry to have wasted everybody's time. Thank you.