我试图用fetch来发送一个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's json echo][2]时,我希望看到我发送的对象({a: 1, b: 2}
)回来,但这并没有发生--chrome devtools甚至没有显示JSON作为请求的一部分,这意味着它没有被发送。
有了ES2017async/await
支持,这就是如何POST
一个JSON有效载荷。
(async () => {
const rawResponse = await fetch('https://httpbin.org/post', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({a: 1, b: 'Textual content'})
});
const content = await rawResponse.json();
console.log(content);
})();
不能使用ES2017?见@vp_art'的使用承诺的答案
不过,这个问题问的是一个由**一个早已修复的chrome bug引起的问题。 原始答案如下。
chrome devtools甚至不显示JSON作为请求的一部分。
这是真正的问题,它是一个chrome devtools的bug,在Chrome 46中修复。
这段代码运行良好--它正确地发布了JSON,只是无法看到它。
我希望能看到我送回的对象。
这并不奏效,因为这不是JSfiddle'的正确格式。
正确的代码][5]是。
var payload = {
a: 1,
b: 2
};
var data = new FormData();
data.append( "json", JSON.stringify( payload ) );
fetch("/echo/json/",
{
method: "POST",
body: data
})
.then(function(res){ return res.json(); })
.then(function(data){ alert( JSON.stringify( data ) ) })
对于接受JSON有效载荷的端点,原代码是正确的。
从搜索引擎上看,我最终找到了这个关于用fetch发布非json数据的主题,所以我想我应该补充一下这个。
对于非json,你不需要使用表单数据。你可以简单地将 "Content-Type "标题设置为 "application/x-www-form-urlencoded "并使用一个字符串。
fetch('url here', {
method: 'POST',
headers: {'Content-Type':'application/x-www-form-urlencoded'}, // this line is important, if this content-type is not set it wont work
body: 'foo=bar&blah=1'
});
另一种建立body'字符串的方法,而不是像我上面那样打出来,是使用库。例如,使用[
query-string](https://www.npmjs.com/package/query-string)或[
qs](https://www.npmjs.com/package/qs)软件包中的
stringify`函数。因此,使用这个方法,看起来就像。
import queryString from 'query-string';
fetch('url here', {
method: 'POST',
headers: {'Content-Type':'application/x-www-form-urlencoded'}, // this line is important, if this content-type is not set it wont work
body: queryString.stringify({for:'bar', blah:1}
});
在花了一些时间,对jsFiddle进行逆向工程,试图生成有效载荷--有一个效果。
请注意 "return response.json(); "一行,这里的response不是一个响应,而是一个承诺。
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:
& & Firefox > 39 & & Chrome > 42