Menu

Content types

“How the server tells the client what's in the body.”

View .md

A response body is just bytes. The Content-Type header tells the client how to interpret them.

http
1HTTP/1.1 200 OK
2Content-Type: application/json; charset=utf-8
3Content-Length: 52
4
5{"id": 7, "title": "Learn HTTP", "completed": false}

Common types#

Content-TypeWhat’s in the body
text/htmlA web page
text/cssA stylesheet
text/javascriptA script
application/jsonJSON data
image/png, image/webpImages
application/pdfA PDF document
application/octet-stream“Just bytes”, usually triggers a download

The same bytes can mean different things. Serve <h1>Hi</h1> as text/html and the browser renders a heading; serve it as text/plain and you see the tags.

Warning

If you set the wrong type, browsers may refuse the file. A script served as text/plain won’t run. A missing type can make some browsers guess (“sniff”), which is why servers also send X-Content-Type-Options: nosniff.

Content negotiation#

The client says what it prefers with Accept; the server picks the best match. That’s called content negotiation:

bash
curl -H "Accept: application/json" https://httpbin.org/get

Some APIs return HTML to browsers and JSON to code from the same URL this way.

Reading the body in JavaScript#

fetch gives you methods for each kind of body:

js
 1const res = await fetch(url);
 2
 3const type = res.headers.get("Content-Type") ?? "";
 4if (type.includes("application/json")) {
 5  const data = await res.json();    // parsed object
 6} else if (type.startsWith("text/")) {
 7  const text = await res.text();    // string
 8} else {
 9  const blob = await res.blob();    // binary, e.g. an image
10}

Note

A body can only be read once. Calling res.json() after res.text() throws. Use res.clone() if you need it twice.

Byte check

0/3

Answer these 3 questions to commit this byte to your learning path.

  1. The server sends <h1>Hi</h1> with Content-Type: text/plain. What do you see?
  2. Which request header asks the server for a specific format?
  3. You call res.text() and then res.json() on the same response. What happens?
Search posts and bytes

Optional account

Keep your progress everywhere

Everything on AminBytes is free to read, with or without an account. Sign in only if you want your commits, streak and merged topics saved, on every device.

or

We keep only your name, avatar and which bytes you finished, and you can delete it all anytime. Privacy