How to Send JSON Data in Fetch in JavaScript
To send JSON data with
fetch in JavaScript, set the method to POST (or another HTTP method), add a Content-Type: application/json header, and use JSON.stringify() to convert your data object to a JSON string in the body option.Syntax
The basic syntax to send JSON data with fetch includes specifying the HTTP method, headers, and the JSON stringified body.
- method: HTTP method like
POSTorPUT. - headers: Include
Content-Type: application/jsonto tell the server you are sending JSON. - body: Use
JSON.stringify()to convert your JavaScript object to a JSON string.
javascript
fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(dataObject) })
Example
This example sends a JSON object with user information to a server endpoint using fetch. It shows how to set headers and stringify the data.
javascript
const url = 'https://example.com/api/users'; const data = { name: 'Alice', age: 30 }; fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(result => console.log('Success:', result)) .catch(error => console.error('Error:', error));
Output
Success: { /* server response JSON object */ }
Common Pitfalls
Common mistakes when sending JSON data with fetch include:
- Not setting the
Content-Typeheader toapplication/json, so the server doesn't recognize the data format. - Forgetting to use
JSON.stringify()on the data object, which causes the body to send as[object Object]. - Not handling the promise returned by
fetchproperly, missing errors or response parsing.
javascript
/* Wrong way: Missing Content-Type and no JSON.stringify */ fetch(url, { method: 'POST', body: data // data is a JS object, not string }); /* Right way: Set header and stringify */ fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) });
Quick Reference
| Option | Description | Example |
|---|---|---|
| method | HTTP method to use | 'POST', 'PUT', 'PATCH' |
| headers | HTTP headers, set Content-Type for JSON | { 'Content-Type': 'application/json' } |
| body | Data sent as JSON string | JSON.stringify({ key: 'value' }) |
| then() | Handle response promise | .then(response => response.json()) |
| catch() | Handle errors | .catch(error => console.error(error)) |
Key Takeaways
Always set the 'Content-Type' header to 'application/json' when sending JSON data.
Use JSON.stringify() to convert your JavaScript object into a JSON string for the request body.
Specify the HTTP method like 'POST' or 'PUT' in the fetch options.
Handle the fetch promise with then() and catch() to process the response and errors.
Forgetting headers or stringifying data are the most common mistakes.