Search code examples
javascriptphpgoogle-chrome-extensionrequestfetch

JavaScript - POST to URL not sending data


I'm trying to send POST data from a Chrome extension to a website controlled by me. However, when sending the POST data I don't receive any.

I'm sending it using this function:

async function httpPost(url, data) {
    const response = await fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    });
    return response.json();
}

It is being called like so:

const post = await httpPost("https://example.com/api", extracted);

Where extracted contains something similar to {entries: [], total: 0 }.

I've tried console.log on httpPost, response, post which did not gave anything useful besides that they're working correct.

On the server side, doing a isset for $_POST does work. The request is sending and is being received. However, doing file_put_contents('test.txt', print_r($_POST)); leaves the file empty. It is being accessed, just empty.

CORS Headers are set:

header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 1000");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");
header("Access-Control-Allow-Methods: *");
header('Content-Type: application/json');

What could this very frustrating issue be?

Desired output: Being able to receive the POST data that I sent with httpPost.


Solution

  • See https://www.php.net/manual/en/function.print-r.php - if you want to capture the output of print_r into a string (so you can write it to a file, for example!) You need to set the return parameter, as noted in the documentation. Right now that's probably just printing the post variables back into the AJAX response, instead of into the file.

    E.g. try this:

    file_put_contents('test.txt', print_r($_POST, true));
    

    Edit:

    Since you're actually sending JSON in the request, none of the above is particularly applicable anyway.

    Similar to the answer in Receive JSON POST with PHP

    you would read in the JSON data into a string, like this:

    $json = file_get_contents('php://input');
    

    Now, to process this in general, you'd run json_decode() on it to turn it into a PHP variable (object, or array depending on the exact content and your preference). But if you simply want to write this data into a file, you might as well just write the raw JSON directly, so you could simply do this:

    file_put_contents('test.txt', $json);