HTTP Form Data And Json Body (Enctype)


  1. 說明
    1. Form Data
    2. Json Body
    3. Enctype Multipart
  2. Postman Body Content-Type

說明 HTTP Form Data 與 Json Body 的差別、使用時機以及程式碼範例。

logo

說明

form.html

<form action="/login" method="post">
  <label for="username">Username:</label>
  <input type="text" id="username" name="username">
  <label for="password">Password:</label>
  <input type="password" id="password" name="password">
  <button type="submit">Login</button>
</form>

Form Data

Form Data

使用下列方式與直接使用 Submit Button 的差別在於不會轉導頁面,但 Content-Type 都是相同的 application/x-www-form-urlencoded

$(document).ready(function() {
  $("#myForm").submit(function(event) {
    event.preventDefault();
    var formData = $("#myForm").serialize();
    $.ajax({
      type: "POST",
      url: "/login",
      data: formData,
      success: function(response) {
        console.log(response);
      },
      error: function(error) {
        console.error(error);
      }
    });
  });
});

Form Data Http Request

POST /api/user HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded

name=David&email=David@example.com&age=25

前端框架通常都以 application/json 的方式的方式送出與接收資料,如果要使用 application/x-www-form-urlencoded 的方式,可以使用 FormData API 來處理。

Json Body

Json Body

$(document).ready(function() {
  $("#myForm").submit(function(event) {
    event.preventDefault();
    var formData = {};
    $("#myForm input").each(function() {
      formData[this.name] = this.value;
    });
    var jsonData = JSON.stringify(formData);
    $.ajax({
      type: "POST",
      url: "/login",
      data: jsonData,
      contentType: "application/json",
      success: function(response) {
        console.log(response);
      },
      error: function(error) {
      }
    });
  });
});

Json Body Http Request

POST /api/user HTTP/1.1
Host: example.com
Content-Type: application/json

{
  "name": "David",
  "email": "David@example.com",
  "age": 25
}

Enctype Multipart

僅供參考上傳檔案時所使用的 EnctypeMultipart,範例的 Http Request 內容。

Form Data with Enctype Multipart

POST /api/upload HTTP/1.1
Host: example.com
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryyrV7KO0BoCBuDbTL

WebKitFormBoundaryyrV7KO0BoCBuDbTL
Content-Disposition: form-data; name="title"

Example title
WebKitFormBoundaryyrV7KO0BoCBuDbTL
Content-Disposition: form-data; name="file"; filename="example.png"
Content-Type: image/png

[Binary data of the image goes here]
WebKitFormBoundaryyrV7KO0BoCBuDbTL--

Postman Body Content-Type

在 Postman 的 Body 選擇 Content-Type,會在 Header 自動對應,不一致時以 Body Content-Type 為主。

Postman HTTP
x-www-form-urlencoded application/x-www-form-urlencoded
form-data multipart/form-data
raw text/plain or application/json
Binary application/octet-stream
GraphQL application/graphql or application/json