Menu
Content types
“How the server tells the client what's in the body.”
A response body is just bytes. The Content-Type header tells the client how to interpret them.
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-Type | What’s in the body |
|---|---|
text/html | A web page |
text/css | A stylesheet |
text/javascript | A script |
application/json | JSON data |
image/png, image/webp | Images |
application/pdf | A 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:
curl -H "Accept: application/json" https://httpbin.org/getSome 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:
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.
Answer these 3 questions to commit this byte to your learning path.
Reset. This byte isn't committed any more. Answer the questions again to commit it.
$ git commit -m "learn(http): Content types"
[main d28e26d] learn(http): Content types
1 byte changed, 3 insertions(+)
See it on your path Already committed . Try the questions again any time, it won't undo anything. To uncommit it and start over: