817

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

4

16 回答 16

898

借助 ES2017async/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);
})();

不能使用 ES2017?使用承诺查看@vp_art 的答案

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

chrome devtools 甚至没有将 JSON 显示为请求的一部分

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

该代码工作正常 - 它正确地发布 JSON,它只是看不到。

我希望看到我发回的对象

这不起作用,因为这不是JSfiddle 的 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 有效负载的端点,原始代码是正确的

于 2015-04-23T12:34:29.840 回答
295

我认为您的问题是jsfiddle只能处理form-urlencoded请求。

但是发出 json 请求的正确方法是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-27T18:20:17.537 回答
97

从搜索引擎中,我最终在这个主题上使用 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-stringqs包的函数。所以使用它看起来像:

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
});
于 2017-02-18T07:15:38.953 回答
48

在花费了一些时间后,对 jsFiddle 进行了逆向工程,试图生成有效载荷 - 有效果。

请注意(小心)在线return response.json();响应不是响应 - 这是承诺。

var json = {
    json: JSON.stringify({
        a: 1,
        b: 2
    }),
    delay: 3
};

fetch('/echo/json/', {
    method: 'post',
    headers: {
        'Accept': 'application/json, text/plain, */*',
        'Content-Type': 'application/json'
    },
    body: 'json=' + encodeURIComponent(JSON.stringify(json.json)) + '&delay=' + json.delay
})
.then(function (response) {
    return response.json();
})
.then(function (result) {
    alert(result);
})
.catch (function (error) {
    console.log('Request failed', error);
});

jsFiddle: http: //jsfiddle.net/egxt6cpz/46/ && 火狐 > 39 && Chrome > 42

于 2015-04-21T17:07:32.353 回答
26

2021 年回答:以防万一您来到这里寻找如何使用 async/await 或 Promise 进行 GET 和 POST Fetch api 请求(与 axios 相比)。

我正在使用 jsonplaceholder fake API 来演示:

使用 async/await 获取 api GET 请求:

         const asyncGetCall = async () => {
            try {
                const response = await fetch('https://jsonplaceholder.typicode.com/posts');
                 const data = await response.json();
                // enter you logic when the fetch is successful
                 console.log(data);
               } catch(error) {
            // enter your logic for when there is an error (ex. error toast)
                  console.log(error)
                 } 
            }


          asyncGetCall()

使用 async/await 获取 api POST 请求:

    const asyncPostCall = async () => {
            try {
                const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
                 method: 'POST',
                 headers: {
                   'Content-Type': 'application/json'
                   },
                   body: JSON.stringify({
             // your expected POST request payload goes here
                     title: "My post title",
                     body: "My post content."
                    })
                 });
                 const data = await response.json();
              // enter you logic when the fetch is successful
                 console.log(data);
               } catch(error) {
             // enter your logic for when there is an error (ex. error toast)

                  console.log(error)
                 } 
            }

asyncPostCall()

使用 Promises 获取请求:

  fetch('https://jsonplaceholder.typicode.com/posts')
  .then(res => res.json())
  .then(data => {
   // enter you logic when the fetch is successful
    console.log(data)
  })
  .catch(error => {
    // enter your logic for when there is an error (ex. error toast)
   console.log(error)
  })

使用 Promises 的 POST 请求:

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
   body: JSON.stringify({
     // your expected POST request payload goes here
      title: "My post title",
      body: "My post content."
      })
})
  .then(res => res.json())
  .then(data => {
   // enter you logic when the fetch is successful
    console.log(data)
  })
  .catch(error => {
  // enter your logic for when there is an error (ex. error toast)
   console.log(error)
  })  

使用 Axios 获取请求:

        const axiosGetCall = async () => {
            try {
              const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts')
    // enter you logic when the fetch is successful
              console.log(`data: `, data)
           
            } catch (error) {
    // enter your logic for when there is an error (ex. error toast)
              console.log(`error: `, error)
            }
          }
    
    axiosGetCall()

使用 Axios 的 POST 请求:

const axiosPostCall = async () => {
    try {
      const { data } = await axios.post('https://jsonplaceholder.typicode.com/posts',  {
      // your expected POST request payload goes here
      title: "My post title",
      body: "My post content."
      })
   // enter you logic when the fetch is successful
      console.log(`data: `, data)
   
    } catch (error) {
  // enter your logic for when there is an error (ex. error toast)
      console.log(`error: `, error)
    }
  }


axiosPostCall()
于 2021-05-16T14:52:19.817 回答
19

如果您使用的是纯 json REST API,我已经围绕 fetch() 创建了一个瘦包装器,并进行了许多改进:

// Small library to improve on fetch() usage
const api = function(method, url, data, headers = {}){
  return fetch(url, {
    method: method.toUpperCase(),
    body: JSON.stringify(data),  // send it as stringified json
    credentials: api.credentials,  // to keep the session on the request
    headers: Object.assign({}, api.headers, headers)  // extend the headers
  }).then(res => res.ok ? res.json() : Promise.reject(res));
};

// Defaults that can be globally overwritten
api.credentials = 'include';
api.headers = {
  'csrf-token': window.csrf || '',    // only if globally set, otherwise ignored
  'Accept': 'application/json',       // receive json
  'Content-Type': 'application/json'  // send json
};

// Convenient methods
['get', 'post', 'put', 'delete'].forEach(method => {
  api[method] = api.bind(null, method);
});

要使用它,您有变量api和 4 种方法:

api.get('/todo').then(all => { /* ... */ });

在一个async函数中:

const all = await api.get('/todo');
// ...

jQuery 示例:

$('.like').on('click', async e => {
  const id = 123;  // Get it however it is better suited

  await api.put(`/like/${id}`, { like: true });

  // Whatever:
  $(e.target).addClass('active dislike').removeClass('like');
});
于 2017-07-17T21:41:32.800 回答
13

这与Content-Type. 正如您可能已经从其他讨论和对这个问题的回答中注意到的那样,有些人能够通过设置来解决它Content-Type: 'application/json'。不幸的是,在我的情况下它不起作用,我的 POST 请求在服务器端仍然是空的。

但是,如果您尝试使用 jQuery$.post()并且它正在工作,原因可能是因为 jQuery 使用Content-Type: 'x-www-form-urlencoded'而不是application/json.

data = Object.keys(data).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(data[key])).join('&')
fetch('/api/', {
    method: 'post', 
    credentials: "include", 
    body: data, 
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
于 2017-07-27T08:52:05.277 回答
13

有同样的问题 - 没有body从客户端发送到服务器。

添加Content-Type标题为我解决了它:

var headers = new Headers();

headers.append('Accept', 'application/json'); // This one is enough for GET requests
headers.append('Content-Type', 'application/json'); // This one sends body

return fetch('/some/endpoint', {
    method: 'POST',
    mode: 'same-origin',
    credentials: 'include',
    redirect: 'follow',
    headers: headers,
    body: JSON.stringify({
        name: 'John',
        surname: 'Doe'
    }),
}).then(resp => {
    ...
}).catch(err => {
   ...
})
于 2017-10-21T07:27:12.257 回答
8

最佳答案不适用于 PHP7,因为它的编码错误,但我可以用其他答案找出正确的编码。此代码还发送身份验证 cookie,您在处理例如 PHP 论坛时可能需要它:

julia = function(juliacode) {
    fetch('julia.php', {
        method: "POST",
        credentials: "include", // send cookies
        headers: {
            'Accept': 'application/json, text/plain, */*',
            //'Content-Type': 'application/json'
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" // otherwise $_POST is empty
        },
        body: "juliacode=" + encodeURIComponent(juliacode)
    })
    .then(function(response) {
        return response.json(); // .text();
    })
    .then(function(myJson) {
        console.log(myJson);
    });
}
于 2018-05-24T04:25:21.540 回答
4

我认为,我们不需要将 JSON 对象解析为字符串,如果远程服务器接受 json 到他们的请求中,只需运行:

const request = await fetch ('/echo/json', {
  headers: {
    'Content-type': 'application/json'
  },
  method: 'POST',
  body: { a: 1, b: 2 }
});

比如 curl 请求

curl -v -X POST -H 'Content-Type: application/json' -d '@data.json' '/echo/json'

如果远程服务器不接受 json 文件作为正文,只需发送一个 dataForm:

const data =  new FormData ();
data.append ('a', 1);
data.append ('b', 2);

const request = await fetch ('/echo/form', {
  headers: {
    'Content-type': 'application/x-www-form-urlencoded'
  },
  method: 'POST',
  body: data
});

比如 curl 请求

curl -v -X POST -H 'Content-type: application/x-www-form-urlencoded' -d '@data.txt' '/echo/form'
于 2018-03-27T15:47:16.937 回答
3

它可能对某人有用:

我遇到了没有为我的请求发送表单数据的问题

在我的情况下,以下标题的组合也导致了问题和错误的 Content-Type。

因此,我将这两个标头与请求一起发送,当我删除有效的标头时,它没有发送表单数据。

"X-Prototype-Version" : "1.6.1",
"X-Requested-With" : "XMLHttpRequest"

此外,其他答案表明 Content-Type 标头需要正确。

对于我的请求,正确的 Content-Type 标头是:

“内容类型”:“应用程序/x-www-form-urlencoded;charset=UTF-8”

因此,如果您的表单数据未附加到请求中,那么底线可能是您的标题。尝试将您的标题减少到最低限度,然后尝试逐个添加它们以查看您的问题是否已解决。

于 2018-03-12T16:47:07.967 回答
3

使用 await/async 可以做得更好。

http请求的参数:

const _url = 'https://jsonplaceholder.typicode.com/posts';
let _body = JSON.stringify({
  title: 'foo',
  body: 'bar',
  userId: 1,
});
  const _headers = {
  'Content-type': 'application/json; charset=UTF-8',
};
const _options = { method: 'POST', headers: _headers, body: _body };

使用干净的 async/await 语法:

const response = await fetch(_url, _options);
if (response.status >= 200 && response.status <= 204) {
  let data = await response.json();
  console.log(data);
} else {
  console.log(`something wrong, the server code: ${response.status}`);
}

使用老式 fetch().then().then():

fetch(_url, _options)
  .then((res) => res.json())
  .then((json) => console.log(json));
于 2021-05-08T15:20:44.763 回答
2

如果您的 JSON 有效负载包含数组和嵌套对象,我会使用URLSearchParams jQuery 的param()方法。

fetch('/somewhere', {
  method: 'POST',
  body: new URLSearchParams($.param(payload))
})

对你的服务器来说,这看起来像是一个标准的 HTML<form>POST编辑。

于 2018-09-07T17:53:05.507 回答
0

您只需要检查响应是否正常,因为呼叫没有返回任何内容。

var json = {
    json: JSON.stringify({
        a: 1,
        b: 2
    }),
    delay: 3
};

fetch('/echo/json/', {
    method: 'post',
    headers: {
        'Accept': 'application/json, text/plain, */*',
        'Content-Type': 'application/json'
    },
    body: 'json=' + encodeURIComponent(JSON.stringify(json.json)) + '&delay=' + json.delay
})
.then((response) => {if(response.ok){alert("the call works ok")}})
.catch (function (error) {
    console.log('Request failed', error);
});    
于 2020-11-10T10:02:02.103 回答
0

我的简单目标是 js object ->-> php $_POST

Object.defineProperties(FormData.prototype, { // extend FormData for direct use of js objects
    load: {
       value: function (d) {
                   for (var v in d) {
                      this.append(v, typeof d[v] === 'string' ? d[v] : JSON.stringify(d[v]));
                   }
               }
           }
   })

var F = new FormData;
F.load({A:1,B:2});

fetch('url_target?C=3&D=blabla', {
        method: "POST", 
          body: F
     }).then( response_handler )
于 2021-04-27T09:44:22.113 回答
-1

您可以使用fill-fetch,它是fetch. 简单地说,您可以发布如下数据:

import { fill } from 'fill-fetch';

const fetcher = fill();

fetcher.config.timeout = 3000;
fetcher.config.maxConcurrence = 10;
fetcher.config.baseURL = 'http://www.github.com';

const res = await fetcher.post('/', { a: 1 }, {
    headers: {
        'bearer': '1234'
    }
});
于 2020-08-25T03:34:31.867 回答