Home >Web Front-end >JS Tutorial >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!