gpt4 book ai didi

Javascript fetch api 有效负载未传递

转载 作者:行者123 更新时间:2023-12-02 21:31:47 24 4
gpt4 key购买 nike

console.log("data ", data); // returns an object in JSON format {propertyName: propertyValue}
dataString = JSON.stringify(dataString); //correctly stringified json

let response = await fetch('updateRecevingEntry.php',
{
method:'POST',
headers: {'Content-Type':'application/json'},
body: dataString
}).then(response=>response.json());

但是我在 php 端得到了一个 undefined index 。

php 所在位置:

$matkey = $_POST['materialKey'];

返回

<b>Notice</b>:  Undefined index: materialKey in <b>path/updateRecevingEntry.php</b> on line <b>3</b><br />

对于所有数据...没有一个被捕获。

那么为什么 _POST['propertyName'] 没有从正文中捕获 stringData?

我尝试了一些变体,例如发送数据而不是与 header 混淆的字符串数据,但我似乎无法弄清楚如何发送有效负载,以便 _POST['propertyName'] 捕获体内的数据。

我之前使用 jquery 中的 $.ajax,并且它工作正常:但我正在重构它。

Fetch api 对我来说是新的。我哪里出错了。我也不想在 php 端解析 json 对象。

阅读其中一个答案后,我让它在一种情况下发挥作用,但是

        let response = await fetch('updateRecevingEntry.php', 
{
method:'POST',
headers: {'Content-Type':'application/json'},
body: sendData
}).then(response=>response.json());

和 php

$postData = json_decode(file_get_contents("php://input"), true);
var_dump($postData);

只返回一个大的NULL。

编辑二:事实证明它实际上只需要通过 JSON.stringify(sendData) 进行编码。自从.它按预期工作。

最佳答案

我注意到的第一件事是您没有使用正确的变量(您使用的是 stringData 而不是 dataString):

dataString = JSON.stringify(dataString); //correctly stringified json

let response = await fetch('updateRecevingEntry.php', {
method:'POST',
headers: {'Content-Type':'application/json'},
body: dataString
}).then(response=>response.json());

尽管您不需要将其字符串化,因为您使用 json header 发送它。

<小时/>

此外,您是否尝试过使用 php://input 来代替 $_POST

来自PHP.net :

php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data".

所以你会像这样使用它:

$postData = json_decode(file_get_contents("php://input"), true);
$matkey = $postData['materialKey'];

这会将 POST 请求的正文读取为 JSON 字符串,然后将其转换为 PHP 数组。

关于Javascript fetch api 有效负载未传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60605553/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com