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
Susan SarandonOriginal
2024-12-11 04:14:14937browse

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

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!

Statement:
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