HTTP(HyperText Transfer Protocol)是「超文字傳輸協定」,是網頁瀏覽器與伺服器溝通的語言。
簡單來說,每當你打開一個網站、按一個連結、送出一個表單時,瀏覽器都會偷偷幫你送出一個HTTP 請求(Request),伺服器再回你一個HTTP 回應(Response),你看到的網頁就是這樣來的
HTTP Request: -> 後端
前端 <- HTTP Response
一個標準的 HTTP Request 由三個部分組成:
(1) 起始行(Request Line)
(2) 標頭(Headers)
(3) 主體(Body) ← 有些請求沒有這一段
例如,當你在網頁上按下搜尋,瀏覽器可能送出的請求會長這樣:
GET /search?q=apple HTTP/1.1
Host: www.google.com
User-Agent: Chrome/120
Accept-Language: zh-TW
解讀:
GET /search?q=apple HTTP/1.1
:請求的第一行,表示方法、路徑與協定版本。Host:
、User-Agent:
、Accept-Language:
:這些是 HTTP 標頭(Header)。方法 | 功能說明 | 有無 Body | 典型用途 |
---|---|---|---|
GET | 取得資料(讀取) | 無 | 載入網頁、查詢資料 |
POST | 送出資料(新增) | 有 | 表單送出、登入 |
PUT | 取代(整筆更新) | 有 | API 資料更新 |
PATCH | 部分更新資料 | 有 | API 局部更新 |
DELETE | 刪除資料 | 視情況 | 刪除資源 |
HEAD | 跟 GET 類似但不回傳 Body | 無 | 檢查資源存在與 Header |
OPTIONS | 詢問伺服器支援哪些方法 | 無 | CORS 預檢請求、偵測 API 能力 |
Header 名稱 | 作用 |
---|---|
Host |
告訴伺服器要存取哪個主機(尤其同 IP 多網站) |
User-Agent |
說明使用的瀏覽器或應用程式 |
Accept / Accept-Language |
告訴伺服器希望回傳什麼格式或語言 |
Cookie |
附帶之前伺服器設定的 cookie(例如登入狀態) |
Content-Type |
如果有 Body,這裡會說明 Body 格式(例如 JSON、表單) |
Authorization |
驗證資訊(例如 Bearer Token、Basic Auth) |
有些請求會在最後夾帶一段資料 → 這就是 Body。
例如登入表單(POST):
POST /login HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 27
username=ken&password=1234
或 JSON API:
POST /api/user HTTP/1.1
Host: api.example.com
Content-Type: application/json
{"name":"Ken","age":18}
用 curl
這個工具在終端機手動送請求
curl -v https://example.com
curl -X POST https://httpbin.org/post -d "name=Ken&age=18"
curl -X POST https://httpbin.org/post \
-H "Content-Type: application/json" \
-d '{"msg":"hello"}'
curl -H "Authorization: Bearer mytoken" https://api.example.com/data
F12
或 Ctrl+Shift+I
開啟開發者工具Authorization
header 常攜帶 Bearer Token,必須妥善保護,不可在前端外洩。OPTIONS
請求預先詢問伺服器,判斷跨域是否被允許。