Sending JSON Data
What you'll learn: How to configure fetch() to send JSON in the request body with the correct headers so the server can parse it.
Why JSON in the Request Body?
When you need to send structured data to a server—like a new user registration, a blog post, or settings—JSON is the standard format. But you can't just pass a JavaScript object directly; you need to convert it to a JSON string and tell the server what format you're sending.
The Two-Step Process
1. Stringify Your Data
Convert your JavaScript object to a JSON string using JSON.stringify():
const userData = {
name: "Alice",
email: "alice@example.com",
age: 28
};
const jsonString = JSON.stringify(userData);
2. Configure Fetch with Method, Body, and Headers
Use the fetch() options object to specify:
- method: typically
'POST'or'PUT' - body: your JSON string
- headers: tell the server the content type
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(userData)
})
.then(response => response.json())
.then(data => console.log('Server responded:', data));
Why the Content-Type Header Matters
Think of Content-Type: application/json as labeling a package before shipping. Without it, the server might misinterpret your data as plain text or form data, causing parsing errors.
Complete Pattern
const newPost = { title: "Hello", content: "World" };
fetch('/api/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(newPost)
});
Key Takeaway: To send JSON via fetch(), stringify your object, set the HTTP method, include the Content-Type: application/json header, and pass the stringified data as the body.