JavaScript - POST 至 URL 未发送数据

JavaScript - POST to URL not sending data

我正在尝试将 POST 数据从 Chrome 扩展程序发送到由我控制的网站。但是,发送 POST 数据时我没有收到任何数据。

我正在使用此功能发送它:

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

它是这样调用的:

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

其中 extracted 包含类似于 {entries: [], total: 0 } 的内容。

我已经在 httpPostresponsepost 上尝试了 console.log,除了它们工作正常之外没有提供任何有用的东西。

在服务器端,为 $_POST 执行 isset 确实有效。请求正在发送和接收中。但是,执行 file_put_contents('test.txt', print_r($_POST)); 会使文件为空。正在访问中,只是空的。

CORS Headers 已设置:

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');

这个非常令人沮丧的问题是什么?

期望的输出:能够接收我用 httpPost.

发送的 POST 数据

参见 https://www.php.net/manual/en/function.print-r.php - 如果你想将 print_r 的输出捕获到一个字符串中(这样你就可以将它写入一个文件,例如!)你需要设置 return 参数,如文档中所述。现在可能只是将 post 变量打印回 AJAX 响应,而不是打印到文件中。

例如试试这个:

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

编辑:

由于您实际上是在请求中发送 JSON,因此上述 none 无论如何都特别适用。

类似于Receive JSON POST with PHP

中的答案

您可以将 JSON 数据读入字符串,如下所示:

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

现在,要对其进行一般处理,您需要 运行 json_decode() 将其转换为 PHP 变量(对象或数组,具体取决于确切的内容和你的偏好)。但是如果你只是想把这个数据写入一个文件,你也可以直接写原始的 JSON,所以你可以简单地这样做:

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