Home > Web Front-end > JS Tutorial > Why Isn't My Fetch POST Request Sending My JSON Data?

Why Isn't My Fetch POST Request Sending My JSON Data?

Susan Sarandon
Release: 2024-12-13 06:00:21
Original
336 people have browsed it

Why Isn't My Fetch POST Request Sending My JSON Data?

POSTing JSON Data with Fetch

You're attempting to POST a JSON object using Fetch, but encountering an issue where the object isn't sent in the request.

The provided code snippet is an attempt to send a JSON object to a JSON echo endpoint. However, it's not working as expected. The request's body is not properly configured to contain the stringified JSON object.

In ES2017, using async/await, here's how to correctly 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);
})();
Copy after login

This code snippet includes the following key updates:

  • Async/await: The code now leverages async/await for cleaner and more readable async code.
  • Proper Body Configuration: The request's body is now set to the stringified JSON object, ensuring it's correctly transmitted in the request.

By implementing these changes, your fetch request should correctly send the JSON object to the echo endpoint.

The above is the detailed content of Why Isn't My Fetch POST Request Sending My JSON Data?. 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