http请求参数之Query String Parameters、Form Data、Request Payload

HTTP请求中不一样的请求方式和设置不一样的Content-Type时,参数传递的方式会不同,一块儿了解这三种形式:Query String Parameters、Form Data、Request Payload;json

GET请求

Query String Parameters

GET请求时,参数会以url string 的形式进行传递,即?后的字符串则为其请求参数,并以&做为分隔符。 General浏览器

Request URL: http://test.com?from_type=省&from_name='四川省'
Request Method: GET
复制代码

Query String Parametersbash

from_type=省&from_name=‘四川省’
复制代码

Post请求

post请求会出现两种形式的请求体:服务器

FormData

当发起一次Post请求,若未指定Content-type,则默认content-type为application/x-www-form-urlencoded,即参数会以FormData的形式进行传递,不会显示出如今请求URL中。 app

Request Payload

当发起一次post请求,若Content-Type为application/json,则参数会以Request Payload的形式进行传递(数据格式为json),不会显示出如今请求url中。 post

formData()方法

服务器为何会对表单提交和文件上传作特殊处理,由于表单提交数据是名值对的方式,且Content-Type为application/x-www-form-urlencoded,而文件上传服务器须要特殊处理,普通的post请求(Content-Type不是application/x-www-form-urlencoded)数据格式不固定,不必定是名值对的方式,因此服务器没法知道具体的处理方式,因此只能经过获取原始数据流的方式来进行解析。url

当咱们遇到一些文件上传功能时,咱们须要使用原生的formData()来进行数据组装,且content-type须要设置为multipart/formdata http请求头:spa

Request URL: http://test.com/upload
Request Method: POST
复制代码

其中,WebKitFormBoundarysBkB6WoEBvbCRkmh为浏览器随机生成的boundary,做为分隔参数,做用等同于&。code

HTTP POST 表单请求提交时,使用的Content-Type是application/x-www-form-urlencoded,而使用原生AJAX的POST请求若是不指定请求头RequestHeader,默认使用的Content-Type是text/plain;charset=UTF-8。orm

因此,在使用原生AJAX POST请求时,须要明确设置Request Header,即:

xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
复制代码
相关文章
相关标签/搜索