Course contentsShow
← JavaScript
Lesson 2289 of 2,72347. Networking PrimitivesFree lesson

Content-Type Header and Body Matching

Ensuring the Content-Type header matches the actual body format to avoid parsing errors.

Content-Type Header and Body Matching

You'll learn how to align your Content-Type header with the actual request body format to prevent server-side parsing failures.

What This Means

When you send data with fetch(), the server uses the Content-Type header to decide how to parse your request body. If you say "this is JSON" but send plain text, or claim "this is form data" but send JSON, the server will fail to process your request correctly—often returning cryptic 400 or 500 errors.

Think of it like labeling a shipping box: if you write "FRAGILE GLASS" on a box full of books, the recipient will open it expecting glassware and be completely confused. The label (header) must match the contents (body).

The Critical Rule

Your Content-Type header must match what you actually put in the body:

  • JSON body → "Content-Type": "application/json"
  • FormData body → usually auto-set to "multipart/form-data" (don't set manually)
  • URLSearchParams body → "Content-Type": "application/x-www-form-urlencoded"
  • Plain text body → "Content-Type": "text/plain"

When you use JSON.stringify() in the body, the server expects JSON. When you pass a FormData object, the browser automatically sets the correct multipart header (including boundary markers). Mismatches cause the server's parser to choke.

Common Mistake

Forgetting to stringify JSON but claiming it's JSON, or manually setting Content-Type for FormData (which breaks the auto-generated boundary parameter).

Key Takeaway: Always ensure your Content-Type header accurately describes the body format you're sending—the server trusts this label to parse your data correctly, and mismatches cause silent failures or parsing errors.