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

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

问题描述

我正在尝试使用提取来发布JSON对象。

I'm trying to POST a JSON object using fetch.

根据我的理解,我需要将一个字符串化的对象附加到请求的主体,例如:

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天全站免登陆