<p>我正在尝试使用fetch方法POST一个JSON对象。</p>
<p>根据我的理解,我需要将一个字符串化的对象附加到请求的body中,例如:</p>
<pre class="brush:js;toolbar:false;">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) })
</pre>
<p>当使用jsfiddle的JSON echo时,我希望能够看到我发送的对象(<code>{a: 1, b: 2}</code>),但这并没有发生- Chrome开发者工具甚至不显示JSON作为请求的一部分,这意味着它没有被发送。</p>
我认为你的问题是
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));使用ES2017的
async/await支持,这是如何进行POSTJSON数据的方法:(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); })();