JSON Request Bodies
What you'll learn: How to convert JavaScript objects into JSON strings and configure headers so servers correctly interpret your data.
The Problem
When you want to send a JavaScript object to a server—like form data, user preferences, or API commands—you can't just pass the object directly. HTTP messages are text-based, so you need to serialize your object into a string format servers universally understand: JSON.
JSON.stringify()
The JSON.stringify() method transforms any JavaScript value into a JSON-formatted string:
const user = {
name: "Alice",
age: 30,
active: true
};
const jsonBody = JSON.stringify(user);
// Result: '{"name":"Alice","age":30,"active":true}'
This string can now travel over HTTP as the body of your request.
Setting Content-Type
Serializing alone isn't enough—the server needs to know the body contains JSON. That's where the Content-Type header comes in. Set it to application/json to signal the format:
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(user)
});
Without this header, the server might misinterpret your data as plain text or form data, causing parsing errors.
Think of It Like Packaging
Imagine mailing a gift: JSON.stringify() is like wrapping it in a standardized box, and Content-Type is the label that tells the recipient "This contains fragile electronics, handle accordingly." Both steps ensure safe delivery and correct handling.
Key Takeaway:
Always use JSON.stringify() to convert objects into strings and set Content-Type: application/json in your headers when sending JSON payloads—this ensures servers understand and parse your data correctly.