介绍
Request Payload 和 Form Data 是浏览器传输给接口的两种格式,这两种方式浏览器是通过 Content-Type
来进行区分的,如果是 application/x-www-form-urlencoded
,则为 Form Data 方式,如果是 application/json
或 multipart/form-data
,则为 Request Payload 的方式。
开发者工具网络面板
Chrome 96 之前,Request Payload 和 Form Data 信息信息出现在报头边栏里。
比如如下使用 ajax 方式的提交 post 请求得到的响应标头(默认:content-type:text/plain;charset=UTF-8
):
content-type:multipart/form-data
提交 post 请求得到的响应标头:
content-type:application/x-www-form-urlencoded
提交 post 请求得到的响应标头:
Chrome 96 开始,当您想查看网络请求中的 Request Payload 和 Form Data 信息时,可以使用网络面板里面的 Payload(载荷)边栏。
content-type:application/json
提交 post 请求得到的响应标头:
content-type:application/x-www-form-urlencoded
提交 post 请求得到的响应标头:
content-type:application/x-www-form-urlencoded
请求标头代码:
1 | const res = await fetch('https://www.runoob.com/try/ajax/demo_post2.php', { |
content-type:application/json
请求标头代码:
1 | const res = await fetch('https://www.runoob.com/try/ajax/demo_post2.php', { |
可以看到不能得到正确响应,fname
和 lname
没有传递成功,也就是后台只接受 Form Data 的参数,不接受 Request Payload 的参数。
默认请求标头 Content-Type
fetch
默认请求标头为:'Content-Type': 'text/plain;charset=UTF-8'
。所以使用fetch
提交post
或其他非 get
请求时,一定要设置Content-Type
请求标头。axios 默认请求标头为:
'Content-Type': 'application/x-www-form-urlencoded'
。1
2
3
4
5
6
7axios({
method: 'post',
url: 'https://www.runoob.com/try/ajax/demo_post2.php',
data: 'fname=Henry&lname=Ford'
});
// 或者
axios.post('https://www.runoob.com/try/ajax/demo_post2.php', 'fname=Henry&lname=Ford');html 表单
enctype
默认:application/x-www-form-urlencoded
,get
请求时设置enctype
属性其他值会被忽略。1
2
3
4
5<form action="https://www.runoob.com/try/ajax/demo_post2.php" method="post">
<input name="fname">
<input name="lname">
<input type="submit">
</form>