Content-Type for Request Bodies
You'll learn how to tell the server what format your request data is in by setting the correct Content-Type header.
What Is Content-Type?
When you send data to a server (usually with POST, PUT, or PATCH), the server needs to know how to interpret those bytes. Is it JSON? Form data? Plain text? The Content-Type request header tells the server exactly what format your request body uses—like labeling a package so the recipient knows whether it contains fragile glass or sturdy books.
Common Content-Type Values
application/json – Use this when sending JSON data. Most modern REST APIs expect this format:
fetch('/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: 'Alice', age: 30 })
});
application/x-www-form-urlencoded – Use for traditional HTML form submissions (key=value pairs):
fetch('/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: 'username=alice&password=secret123'
});
multipart/form-data – Use when uploading files (handled automatically by FormData objects; you typically don't set this manually).
Why It Matters
Without the correct Content-Type, the server might reject your request (often with a 415 Unsupported Media Type error) or misinterpret your data. It's like speaking French to someone expecting English—the words arrive, but they can't understand them.
Always match your Content-Type to your body format: JSON with application/json, form encoding with application/x-www-form-urlencoded.
Key Takeaway: Always set the Content-Type header to match your request body format—application/json for JSON, application/x-www-form-urlencoded for form data—so the server knows how to parse your payload correctly.