Home > Web Front-end > JS Tutorial > How to Properly Send JSON Data with Fetch POST Requests?

How to Properly Send JSON Data with Fetch POST Requests?

Susan Sarandon
Release: 2024-12-11 04:14:14
Original
935 people have browsed it

How to Properly Send JSON Data with Fetch POST Requests?

Sending JSON Data with Fetch POST

When utilizing the fetch API for posting JSON data, the request's body should contain a stringified version of the desired JSON object. However, you've encountered an issue where the JSON object isn't being sent along with the request.

To resolve this, you can use ES2017's async/await mechanism:

(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);
})();
Copy after login

With this code, the JSON object {a: 1, b: 'Textual content'} will be stringified and attached to the fetch body as expected.

The above is the detailed content of How to Properly Send JSON Data with Fetch POST Requests?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template