Home > Web Front-end > JS Tutorial > How Can I POST JSON Data Using the Fetch API?

How Can I POST JSON Data Using the Fetch API?

Mary-Kate Olsen
Release: 2024-12-11 02:57:14
Original
338 people have browsed it

How Can I POST JSON Data Using the Fetch API?

POSTing JSON Data with Fetch API

It is common practice to send JSON data using the POST request type. You can do this with JavaScript's Fetch API, which provides a powerful interface for making HTTP requests.

One method of sending JSON data via Fetch API is to include a JSON object as the body of the request. To do this, convert the JSON object to a string using JSON.stringify():

const body = JSON.stringify({a: 1, b: 2});
Copy after login

Then, attach this stringified object to the request body:

fetch("/echo/json/", {
    method: "POST",
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: body
})
.then(res => console.log(res))
.catch(res => console.log(res));
Copy after login

However, this method may not work in certain cases, especially when using development tools like jsfiddle's JSON echo. Alternatively, you can use the ES2017 async/await syntax to handle the 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 method converts the response to a JSON object, which can be more effectively queried and processed in your code.

The above is the detailed content of How Can I POST JSON Data Using the Fetch API?. 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