關於HTTP

什麼是HTTP

HTTP 全名是Hypertext Transfer Protocol,中文是超文本傳輸協定,是一個網路應用層的協定,讓電腦之間可以互相傳輸資訊。

HTTP如何運作

HTTP遵循客戶端(client)-伺服器端(server)的模式
client =>(發送請求,request) => server(根據請求內容) =>(發送回應,response)=>client

圖片來源https://bytesofgigabytes.com/networking/how-http-request-and-response-works/

### HTTP的內容 擷取MDN針對這四個部分的概覽:
  • Start Line: A start-line describing the requests to be implemented, or its status of whether successful or a failure. This start-line is always a single line.
    Start Line:描述要實現的請求或其成功或失敗狀態的起始行。 此起始線始終是單行。
  • HTTP headers: An optional set of HTTP headers specifying the request, or describing the body included in the message. Empty Line: A blank line indicating all meta-information for the request has been sent.
    HTTP 標頭:一組可選的 HTTP 標頭,用於指定請求或描述訊息中包含的正文。 空白行:空白行指示請求的所有元資訊已發送。
  • Body: An optional body containing data associated with the request (like content of an HTML form), or the document associated with a response. The presence of the body and its size is specified by the start-line and HTTP headers.
    Body:包含與請求關聯的資料(如 HTML 表單的內容)或與回應關聯的文件的可選正文。 正文的存在及其大小由起始行和 HTTP 標頭指定。

圖片來源:MDN HTTP Messages

Request發送請求

  1. Start Line:包含三個部分
    • Method: 請求的方法,是GET, PUT, POST等等的動詞,不同的動詞有不同的使用場景
    • Request target: 請求的目標 請求的目標,通常是網址,也就是網路資源存放的地方,根據不同的method,會有不同的格式,可以看我之前寫的GET vs. POST的不同。
    • HTTP version request使用的http版本
  2. HTTP headers
    資料來源MDN
    • host: 這個request是send給誰的(server的網址)
    • accept:這個request是要接受哪些類型(content-types)的資料 比方說text或是json檔案
    • cookie:瀏覽器存放的cookie字串
  3. Body: Request的Body一樣會根據不同的method而有所不同,一般來說GET、DELETE不會帶有body,POST則會把資訊放入body裡面。在使用HTML表單時,如果用表單送一個POST request,就會把表單內容放入body。

Response發送回應

  1. Start Line: 一樣包含三個部分,需要注意的是並沒有method和URL
    • HTTP version
    • Status Code: 這是response start line最重要的部分,server利用status code來告訴client這個request到底是成功還是失敗。status code根據不同 資料來源
      1
      2
      3
      4
      5
      - Informational responses (100–199)
      - Successful responses (200–299)
      - Redirects (300–399)
      - Client errors (400–499)
      - Server errors (500–599)
      一般使用者最常看到的就是404:頁面不存在,除了4xx,在開發時常用的還有200 (OK)、3xx (Redirect)、5xx (Server error)。
    • Status text:簡短的和使用者說明status code是什麼意思,比方說404 Not Found。
  2. HTTP headers:列出一些常見的
    • Status: 就是status code,例如200
    • Server: 透過什麼web server來回應的,比方說Apache
    • content-type: 這個response檔案是什麼類型
    • set-cookie: server端要設定在client端的cookie
  3. Body: response的body會帶著server要回傳給client的資料。對前端開發者來說,通常是json檔案,前端開發者要處理的邏輯就是把接收的json檔案轉換成畫面,渲染給終端使用者看