WEB PROTOCOLS · 87
HTTP Message Anatomy:Method、Target、Headers、Body、Status
Browser 顯示一個頁面之前,先交換 HTTP messages。要 debug API、cache、auth、redirect、content-type,你必須能讀 request 與 response,而不是只看畫面。
Learning outcomes
- 能讀 request line / headers / body。
- 能讀 response status / headers / body。
- 能說明 Content-Type、Authorization、Cache-Control 等 header 的角色。
- 能區分 transport success 與 application success。
1. Request
POST /courses HTTP/1.1
Host: api.example.com
Content-Type: application/json
Authorization: Bearer ...
{"title":"JavaScript"}Method + target 描述 operation;headers 帶 metadata/context;body 帶 optional payload。
2. Response
HTTP/1.1 201 Created
Content-Type: application/json
Location: /courses/42
{"id":42,"title":"JavaScript"}Status code 是 protocol-level result;body 則可帶 application data/error details。
3. Content-Type 是 interpretation contract
Content-Type:
application/json
Content-Type:
text/html; charset=utf-8Client parse 方式應與 server 實際 content type/body 一致。API route 若意外回 HTML error page,JSON parser 會爆掉。
4. Headers 不只是附加資訊
Authorization
Cookie
Set-Cookie
Cache-Control
ETag
Location
OriginAuth、cache、redirect、CORS 都大量依賴 headers。
5. HTTP success 仍可能是 business failure
200 只表示 server 以 successful HTTP status 回應,不保證 body 裡的 business rule 一定符合你想要;相反地 4xx/5xx 也可能有完整 JSON error body。
Project checkpoint:Request Map v2
用 DevTools Network 捕捉 GET /courses 與 POST /courses,逐項抄下 method、URL、request headers/body、status、response headers/body。
Request:
method
target
auth
content-type
body
Response:
status
content-type
bodyDebug evidence:Unexpected token < in JSON
這常代表你以為 response 是 JSON,但實際 body 可能是 HTML。先看 Network Response 與 Content-Type,不要先改 JSON.parse。
Knowledge check
- Request body 一定存在嗎?
- Content-Type 解決什麼問題?
- 201 與 200 的語意有何差異?
- 從 Network panel 完整抄一組 request/response。