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); })();
This code snippet includes the following key updates:
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!