【发布时间】:2019-03-19 17:29:38
【问题描述】:
就 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)但我做不到......问题是正文没有发送到服务器(GET 请求正常),不是服务器问题,(我在同一台机器上使用 PHP 7),我调试了请求,根本没有正文内容发送到服务器...
最后,在两个朋友的帮助下,我们意识到,比起使用其他 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”内容类型标头,并为“body”属性使用字符串。
这是 ONLY 在 fetch POST 请求中发送“body”的方式... 是的,当我使用“application/json”标头和 JSON.stringify 作为正文时,我尝试使用很多属性,例如“mode”、“cache”、“credentials”......和“POST”和/或小写的“Content-Type”......以及json数据中的简单双引号......但没有任何效果
【问题讨论】:
-
看看你的开发者工具网络标签中的请求,它绝对有效......数百万人使用它。问题一定出在您的服务器上。
标签: javascript post fetch