Home >Web Front-end >JS Tutorial >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});
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));
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); })();
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!