我正在尝试使用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 的 JSON echo 时,我希望看到我发送回来的对象 (),但这不会发生 – chrome devtools 甚至没有将 JSON 显示为请求的一部分,这意味着它没有被发送。{a: 1, b: 2}
在 ES2017 支持下,这是如何实现 JSON 有效负载的方法:async/await
POST
(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错误引起的问题。
原答案如下。
Chrome devtools甚至没有将JSON显示为请求的一部分。
这是这里真正的问题,它是Chrome devtools的错误,在Chrome 46中修复。
该代码工作正常 – 它正确地发布JSON,只是看不到。
我希望看到我发回的对象
这是行不通的,因为这不是 JSfiddle 回声的正确格式。
正确的代码是:
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 有效负载的终结点,原始代码是正确的
我认为您的问题是只能处理请求。但是发出 json 请求的正确方法是作为一个主体正确传递:jsfiddle
form-urlencoded
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));
从搜索引擎中,我最终选择了这个主题,用于使用 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
stringify
query-string
qs
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
});
模板简介:该模板名称为【JavaScript 中使用fetch发布JSON对象数据】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【JavaScript】栏目查找您需要的精美模板。