javascript - 正文未在 "fetch"POST 请求和(我的)解决方案中发送

标签 javascript post fetch

这个问题在这里已经有了答案:





Receive JSON POST with PHP

(11 个回答)


3年前关闭。




正如 MDN 所说,使用获取和发送数据进行 POST 请求的正确方法是:( https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch )

var url = 'https://example.com/profile';
var data = {username: 'example'};

fetch(url, {
  method: 'POST', // or 'PUT'
  body: JSON.stringify(data), // data can be `string` or {object}!
  headers:{
    'Content-Type': 'application/json'
  }
}).then(res => res.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));

但我花了 2 天时间试图让它工作(Chrome、Firefox、Edge)但我不能......问题是 body 没有发送到服务器(GET 请求工作正常),不是服务器问题,(我'我在同一台机器上使用 PHP 7),我调试了请求并且根本没有正文内容被发送到服务器......

最后,在两位 friend 的帮助下,我们意识到,比起使用其他 header 和其他 body 格式,body 是发送的。这些是我工作的测试文件:
<body>
<button onclick='buttonOneClick()'>One (GET)</button>
<button onclick='buttonTwoClick()'>Two (POST)</button>
<script>
function buttonOneClick(){
    fetch('server.php?text=one&id=1')
        .then(r => r.text())
        .then(res => alert('you sent '+res));
} 
function buttonTwoClick(){

    let data = "text=two&id=1";
    fetch('server.php', {
        method: 'POST',
        body: data,
        headers: {
            'Content-Type':'application/x-www-form-urlencoded',
        },
    })
    .then(r => r.text())
    .then(res => alert('you sent '+res));
}
</script>
</body>

和服务器文件,在 PHP 中:
<?php
$param = $_REQUEST['text'] ?? "nothing";
print $param;

我不得不使用“application/x-www-form-urlencoded”而不是“application/json”内容类型 header ,并为“body”属性使用字符串。

这是仅限 在 fetch POST 请求中发送“body”的方式...
是的,当我使用“application/json” header 和 JSON.stringify 作为正文时,我尝试使用很多属性,例如“mode”、“cache”、“credentials”......和“POST”和/或小写的“Content-Type”......以及json数据中的简单和双引号......但没有任何效果

最佳答案

JSON 正文不是 $_POST 像 PHP afaik 中的常用数据。不过,您应该能够使用此代码段来读取 json。

// Get JSON as a string
$json_str = file_get_contents('php://input');
// Get as an object
$json_obj = json_decode($json_str);

关于javascript - 正文未在 "fetch"POST 请求和(我的)解决方案中发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52814151/

相关文章:

javascript - Google API 请求收到不良结果

javascript - 两个循环之间的区别

javascript - 如何使用 Javascript 从多个 firebase 数据库中获取数据?

objective-c - 使用开始日期获取 iPhone 日历中的所有事件

javascript - 使用这段代码你能实现什么目的?

http - 在 Google App Engine 日志中查看 POST 请求的参数

javascript - 防止后期数据伪造

javascript - 在express/node中使用发布的表单数据时遇到问题

php - 在数组的每个位置获取数组函数加倍值?

PHP 无法识别 Mysql 值