The encType attribute of the form tag is defined and used
The encType attribute specifies how form data should be encoded before being sent to the server. By default, form data will be coded as Application/X-www-form-urlencoded. That is, all characters are encoded (Spaces converted to “+” plus signs, special symbols converted to ASCII HEX values) before being sent to the server
value | describe |
---|---|
application/x-www-form-urlencoded | Encodes all characters before sending (default) |
multipart/form-data | Instead of character encoding, You must use this value when using forms that contain file upload controls |
text/plain | Spaces are converted to “+” plus signs, but no special character encoding |
HTTP/1.1 provides HTTP request methods including OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, and CONNECT.
POST is used to submit data to the server, and GET is used to request data from a specified resource. This article focuses on several ways to POST data and GET requests
HTTP data format
HTTP protocol is an application layer specification based on TCP/IP protocol, which is transmitted by ASCII code. The specification divides an HTTP request into three parts: the status line, the request header, and the message body. The structure is similar to the following:
<method> <request-URL> <version>
<headers>
<entity-body>
Copy the code
The protocol states that the data submitted by a POST must be placed in the entity-body of the message, but it does not specify how the data must be encoded. In fact, it is entirely up to the developer to format the body of the message, as long as the final HTTP request that is sent meets the above format.
However, when the data is sent, it does not make sense until the server has successfully parsed it. Common server-side languages such as PHP and Python, as well as their frameworks, have built-in capabilities to automatically parse common data formats. The server usually uses the Content-Type field in the headers to determine how the body of the message in the request is encoded and then parses the body.
So when it comes to POST submission data scheme, there are two parts: Content-Type and message body encoding.
Demo code preparation
Here we build a simple server based on the Node Express library, which is used to parse various types of requests initiated by the page
Environment requirements: Install nodeJs and NPM install -g serve
The directory structure
| ____form - get | | ____index. HTML / / get request demo | ____index. HTML / / web services portal file | ____. Gitignore | ____package - lock. Json | ____package. Json | ____form - data | | ____index. HTML / / the content-type = > the form - the data request demo | ____application - json | | ____index. HTML / / the content-type = > application - json request demo | ____form - urlencode | | ____index. HTML / / the content-type = > Application/x - WWW - form - urlencoded request demo | | ____serve. Js / / node servicesCopy the code
Serve.js creates a service that listens on local port 3111
const express = require('express')
const app = express()
const port = 3111
app.listen(port, () => {
console.log(`Started at port ${port}`)
})
Copy the code
Switch to the current directory
Start the Web service serve. By default, port 5000 is enabled and the browser accesses localhost:5000
The installation of NPM packages depends on NPM I
Start the Node service node serve.js
application/x-www-form-urlencoded
This is probably the most common way to POST data. A browser’s native
form-urlencode/index.html
<! - note must be post request - > < form action = "http://localhost:3111/form-urlencode" method = "post" enctype="application/x-www-form-urlencoded"> <p>First name: <input type="text" name="fname" /></p> <p>Last name: <input type="text" name="lname" /></p> <input type="submit" value="Submit" /> </form>Copy the code
Go to localhost:5000/form-urlencode/index.html, fill out the form, and click the Submit button
Serve.js code for handling/form-urlenCode requests
Const bodyParser = require('body-parser') // Form-urlencode body const urlencodedParser = bodyParser. Urlencoded ({ extended: false }) app.post('/form-urlencode', urlencodedParser, function (req, res) { console.log('get application/x-www-form-urlencoded Params: ', req.body) res.json({ result: 'success', data: req.body }) })Copy the code
At this time, the request data submitted by Form, the content-Type request header value seen during packet capture is Application/X-www-form-urlencoded
The submitted data is encoded according to key1=val1&key2=val2. Both key and val are URL transcoded. Click view Source next to Form Data in the figure below to see the effect fname=Jack&lname=Chan
The result of the response to the form submission
If you submit data using Ajax instead of forms, use this method. Content-type defaults are application/x-www-form-urlencoded; charset=utf-8
multipart/form-data
This is another common way to POST data. When we use forms to upload files, we must let
multipart/form-data
form-data/index.html
<! -- js through new FormData () to send data in the form through the following demo - > < form action = "http://localhost:3111/form-data" method = "post" enctype="multipart/form-data"> <p>name: <input type="text" name="name" /></p> <p>age : <input type="number" name="age" /></p> <input type="submit" value="Submit" /> </form>Copy the code
Go to localhost:5000/form-data/index.html, fill out the form, and click the Submit button
Serve.js code for handling /form-data requests
Const multipartMiddleware = multipart() const multipartMiddleware = multipart() app.post('/form-data', multipartMiddleware, function (req, res) { console.log('get application/form-data Params: ', req.body) res.json({ result: 'success', data: req.body }) })Copy the code
The result of the response to the form submission
The content-Type request header value of the request submitted by the Form is multipart/form-data
You can also see the form data requested above:
------WebKitFormBoundaryTPENO2DooTSePmIO
Content-Disposition: form-data; name="name"
Jack
------WebKitFormBoundaryTPENO2DooTSePmIO
Content-Disposition: form-data; name="age"
30
------WebKitFormBoundaryTPENO2DooTSePmIO--
Copy the code
Format description:
First, a boundary was generated to divide different fields. In order to avoid repetition with the text, the boundary was very long and complicated.
Then the content-Type indicates that the data is encoded with multipart/form-data, and what is the Content of boundary in this request. The message body is divided into several parts with similar structure according to the number of fields. Each part starts with –boundary followed by the content description information
Next is the carriage return, and finally the field (text or binary). If you are transferring a file, also include the filename and file type information. The message body ends with a –boundary– identifier.
For a detailed definition of multipart/form-data, go to rfc1867
The two methods of Posting data mentioned above are supported natively by browsers, and native forms are only supported in the current standard (specified by the encType attribute of an element, default is Application/X-www-form-urlencoded). Enctype also supports text/plain, though very rarely.)
application/json
Application/JSON The Content-type is increasingly used as a request header to tell the server that the body of the message is a serialized JSON string.
Due to the popularity of the JSON specification, json.stringify is natively supported in every major browser except for earlier versions of IE, and all server-side languages have functions that handle JSON without any trouble.
form-data/application-json.html
<! -- html --> <p>First name: <input type="text" name="fname" /></p> <p>Last name: <button onclick="submit()"> submit </button> <br> <p> <p style="color:red" id="result"></p> </p> <! - the script -- > < script > submit = function () {var fname = document. GetElementsByName (' fname) [0]. Fname var value / / the user input Lname = document. The getElementsByName (' lname) [0]. The value / / the user to enter the lname var XHR = new XMLHttpRequest () / / using HTTP A POST request to the server interaction data XHR. Open (" POST ", "http://localhost:3111/application-json", Application /json xhr.setRequestHeader('content-type', 'application/json') xhr.onreadystatechange = function () { if (xhr.readyState == 4) { document.getElementById('result').innerHTML=JSON.stringify(JSON.parse(xhr.responseText)) console.log() } } var sendData = {fname, lname} // Serialize user input values into a string xhr.send(json.stringify (sendData))} </script>Copy the code
Browser to localhost: 5000 / application – json/index. HTML and fill out the form, click on the Submit button, get back to the package content in figure red arrows renders
Serve.js code for handling /application-json requests
Const bodyParser = require('body-parser') // applica-json body const jsonParser = bodyParser. Json ({extended: False}) /** application-json */ app.post('/application-json', jsonParser, function (req, Res) {console.log('get Application -json Params: ', req.body) res.json({result: 'You sent data is: ', data: req.body})})Copy the code
At this point, the content-type request header value of the request submitted by the interface is Application/JSON, and the Content of the return packet is rendered in red text on the page
The result of the response to the form submission
The application-JSON type can easily submit complex structured data, which is suitable for RESTful interfaces. Various package capture tools such as Chrome’s developer Tools, Fiddler, and Charles display JSON data in a tree structure, which is very friendly.
GET an interface
Finally, the GET interface is attached, which basically covers more than 90% of the interface types in daily development
We use a form to initiate the request
The Get method does not contain “body” and its request parameters are encoded after the URL, so it is useless to include content-Type in the Get method
form-get/index.html
<form action="http://localhost:3111/get" method="get">
<p>name: <input type="text" name="name" /></p>
<p>age : <input type="number" name="age" /></p>
<input type="submit" value="Submit - get" />
</form>
Copy the code
Fill out the form and submit it
The serve.js interface response is also simple, simply fetching req.query without any middleware
App. get('/get', function (req, res) {console.log('get Params: ', req.query) res.json({result: 'You sent data: ', data: req.query }) })Copy the code
The result of the response to the form submission
As you can see, the GET parameter is passed through the URL, concatenated directly into the Query parameter, and there is no Content-Type in the request header
Benefits GET – POST difference
The GET argument is passed through the URL, and the POST is placed in the request body. Get requests pass parameters in the URL with length limits, whereas POST does not. Get is less secure than POST because parameters are directly exposed in the URL and therefore cannot be used to pass sensitive information. Get requests can only be url encoded, while POST supports multiple encoding methods. Get requests are actively cached by the browser, while POST supports multiple encodings. Get request parameters are retained in the browser history, while POST parameters are not. GET and POST are essentially TCP links and are no different. However, due to HTTP regulations and browser/server restrictions, they are applied differently. GET generates a TCP packet; POST generates two TCP packets.Copy the code
See here, do not feel that the daily business interface type is also these, nothing more than doing some database CRUD operations, so, front and back together with it
Reference:Content-type is common in post request headers
Demo source: github.com/melunar
More about me
- 💻 blog
- 🐱 making
- 🔨 nuggets
- 👱 about me
- 🐒 CSDN
The official wechat account stands for Moon