我正在尝试使用以下命令发布一个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回声
我希望看到我发送的对象(
)返回,但这并没有发生- chrome devtools甚至没有将JSON显示为请求的一部分,这意味着它没有被发送。
发布于 2015-04-23 20:34:30
使用ES2017
支持
,这是如何
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
_
艺术的
使用promises回答
然而,这个问题是在询问一个由以下原因引起的问题:
一个很久以前修复的chrome错误。
原始答案如下。
chrome devtools甚至没有将JSON显示为请求的一部分
这才是真正的问题所在
,它是一个
chrome devtools的错误
,已在Chrome 46中修复。
这段代码运行得很好--它正确地POSTing了JSON,只是看不到而已。
我希望看到我发回的对象
这是不起作用的,因为这不是
JSfiddle回显的正确格式
..。
The The The
正确的代码
是:
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有效负载的端点,
原始代码是正确的
发布于 2017-02-28 02:20:18
我觉得你的问题是
can进程
仅限请求。
但是正确的方法是传递正确的json请求
作为一个主体:
fetch('https://httpbin.org/post', {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({a: 7, str: 'Some string: &=&'})
}).then(res => res.json())
.then(res => console.log(res));
发布于 2017-02-18 15:15:39
在搜索引擎中,我在非json发布数据的fetch上讨论了这个话题,所以我想我应该加上这个。
对于
非json
您不必使用表单数据。您可以简单地将
标题至
并使用字符串:
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'
});
另一种构建它的方法
字符串,而不是像上面那样键入字符串,而是使用库。例如,
函数来源
或者
包。因此,使用此代码将如下所示:
import queryString from 'query-string'; // import the queryString class
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}) //use the stringify object of the queryString class
});
https://stackoverflow.com/questions/29775797
复制相似问题