# 常見的 POST 請求 content-type 介紹 ## 四種常見的 POST 請求 content-type 介紹 `想傳送資料給對方伺服器時`,可以透過 POST 方法發送網路請求,<font color="blue">發送時也需要讓對方知道我們傳過去的檔案格式會是什麼</font>。 所以我們會透過 **headers 中的 Content-Type** 告知對方我們要傳送的格式,進而用對應的方式解讀資料。 ★ 觀察 form 表單的編碼方式:[連結](https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_form_enctype) ### 1. form 傳統表單輸入: ```javascript= application/x-www-form-urlencoded ``` `<form>` 標籤的屬性會包含 method。 **method** 可以使用 get 、 post 發送請求,當指定 post 請求後, `<form>`標籤的 enctype 的屬性值會默認使用此方式提交: > enctype 編碼型別: 發送到服務器之前應該如何對表單數據進行編碼 ```javascript= <form action="/action_page_binary.asp" method="post" > <label for="fname">First name:</label> <input type="text" id="fname" name="fname"><br><br> <label for="lname">Last name:</label> <input type="text" id="lname" name="lname"><br><br> <input type="submit" value="Submit"> </form> ``` ### 2. 透過 JSON 格式來傳遞參數資料 目前使用到的 API 都是使用這種 Content-Type ,透過 JSON 格式傳遞。 (p.s.) 透過 `axios` 套件發送網路請求時,默認的 Content-Type 也是此種類型。 ```javascript= application/json ``` ### 3.上傳 「檔案、圖片、影片」 使用表單標籤時,可以透過指定 enctype 屬性為 multipart/form-data 的方式來操作 ```javascript= multipart/form-data ``` ```javascript= <form action="/action_page_binary.asp" method="post" enctype="multipart/form-data"> <label for="fname">First name:</label> <input type="text" id="fname" name="fname"><br><br> <label for="lname">Last name:</label> <input type="text" id="lname" name="lname"><br><br> <input type="submit" value="Submit"> </form> ``` 此為比較進階的 post 用法,如果想更了解 form-data ,請點選此篇 [文章](https://blog.kalan.dev/2021-03-13-html-form-data/)。 4. 純文本格式 ```javascript= text/plain ``` ### 範例練習 <iframe height="300" style="width: 100%;" scrolling="no" title="8/30 (一) - 四種常見的 POST 請求 content-type 介紹" src="https://codepen.io/unayo/embed/abwZZLr?default-tab=js&theme-id=dark" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/unayo/pen/abwZZLr"> 8/30 (一) - 四種常見的 POST 請求 content-type 介紹</a> by unayo (<a href="https://codepen.io/unayo">@unayo</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> ###### tags: `JS` {%hackmd @unayojanni/H1Qq0uKkK %}
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up