我试图使用fetch POST一个JSON对象。
根据我的理解,我需要将一个字符串化的对象附加到请求的主体,例如:
fetch("/echo/json/",
{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify({a: 1, b: 2})
})
.then(function(res){ console.log(res) })
.catch(function(res){ console.log(res) })
当使用jsfiddle的JSON回显时,我希望看到我发送的对象({a: 1, b: 2})回来,但这不会发生- chrome devtools甚至不显示JSON作为请求的一部分,这意味着它没有被发送。
上面的答案对PHP7不起作用,因为它有错误的编码,但我可以用其他答案找出正确的编码。这段代码还发送验证cookie,这可能是你在处理PHP论坛时需要的:
julia = function(juliacode) {
fetch('julia.php', {
method: "POST",
credentials: "include", // send cookies
headers: {
'Accept': 'application/json, text/plain, */*',
//'Content-Type': 'application/json'
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" // otherwise $_POST is empty
},
body: "juliacode=" + encodeURIComponent(juliacode)
})
.then(function(response) {
return response.json(); // .text();
})
.then(function(myJson) {
console.log(myJson);
});
}
在花了一些时间后,反向工程jsFiddle,试图生成有效负载-有一个效果。
请采取眼睛(照顾)在线返回response.json();这里的回应不是回应,而是承诺。
var json = {
json: JSON.stringify({
a: 1,
b: 2
}),
delay: 3
};
fetch('/echo/json/', {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: 'json=' + encodeURIComponent(JSON.stringify(json.json)) + '&delay=' + json.delay
})
.then(function (response) {
return response.json();
})
.then(function (result) {
alert(result);
})
.catch (function (error) {
console.log('Request failed', error);
});
jsFiddle: http://jsfiddle.net/egxt6cpz/46/ && Firefox > 39 && Chrome > 42
它可能对某些人有用:
我遇到的问题是,formdata没有为我的请求发送
在我的案例中,是以下标题的组合也导致了这个问题和错误的Content-Type。
我和请求一起发送了这两个头文件当我删除了工作的头文件时它并没有发送formdata。
"X-Prototype-Version": "1.6.1",
"X-Requested-With": "XMLHttpRequest"
另外,其他答案表明,Content-Type头需要正确。
对于我的请求,正确的Content-Type头是:
“内容类型”:“应用程序/ x-www-form-urlencoded;charset = utf - 8”
所以底线是,如果你的formdata没有附加到Request,那么它可能是你的header。试着减少标题,然后一个一个地添加它们,看看你的问题是否得到解决。
上面的答案对PHP7不起作用,因为它有错误的编码,但我可以用其他答案找出正确的编码。这段代码还发送验证cookie,这可能是你在处理PHP论坛时需要的:
julia = function(juliacode) {
fetch('julia.php', {
method: "POST",
credentials: "include", // send cookies
headers: {
'Accept': 'application/json, text/plain, */*',
//'Content-Type': 'application/json'
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" // otherwise $_POST is empty
},
body: "juliacode=" + encodeURIComponent(juliacode)
})
.then(function(response) {
return response.json(); // .text();
})
.then(function(myJson) {
console.log(myJson);
});
}
这与内容类型有关。正如你可能已经从其他讨论和这个问题的答案中注意到的,有些人能够通过设置Content-Type: 'application/json'来解决这个问题。不幸的是,在我的情况下,它没有工作,我的POST请求在服务器端仍然是空的。
然而,如果你尝试使用jQuery的$.post(),它可以工作,原因可能是因为jQuery使用Content-Type: 'x-www-form-urlencoded'而不是application/json。
data = Object.keys(data).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(data[key])).join('&')
fetch('/api/', {
method: 'post',
credentials: "include",
body: data,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})