获取:POST JSON 数据 [英] Fetch: POST JSON data

查看:48
本文介绍了获取:POST JSON 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 fetch<发布 JSON 对象.

据我所知,我需要在请求正文中附加一个字符串化对象,例如:

From what I can understand, I need to attach a stringified object to the body of the request, e.g.:

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 时,我希望看到我发送的对象({a: 1, b: 2}) 返回,但这不会发生 - chrome devtools 甚至不显示 JSON 作为请求的一部分,这意味着它没有被发送.

When using jsfiddle's JSON echo I'd expect to see the object I've sent ({a: 1, b: 2}) back, but this does not happen - chrome devtools doesn't even show the JSON as part of the request, which means that it's not being sent.

推荐答案

使用 ES2017 async/await 支持,这是如何POST JSON 负载:

With ES2017 async/await support, this is how to POST a JSON payload:

(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 的使用承诺的答案

Can't use ES2017? See @vp_art's answer using promises

然而,问题是询问由长期修复的 chrome 错误引起的问题.
原始答案如下.

The question however is asking for an issue caused by a long since fixed chrome bug.
Original answer follows.

chrome devtools 甚至不显示 JSON 作为请求的一部分

chrome devtools doesn't even show the JSON as part of the request

这是真正的问题,这是一个chrome devtools 的错误,已在 Chrome 46 中修复.

This is the real issue here, and it's a bug with chrome devtools, fixed in Chrome 46.

该代码工作正常 - 它正确地发布了 JSON,只是无法看到.

That code works fine - it is POSTing the JSON correctly, it just cannot be seen.

我希望看到我发回的对象

I'd expect to see the object I've sent back

这不起作用,因为这不是 JSfiddle 的回声的 正确格式.

that's not working because that is not the correct format for JSfiddle's echo.

正确代码是:

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 有效负载的端点,原始代码是正确的

For endpoints accepting JSON payloads, the original code is correct

这篇关于获取:POST JSON 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆