0%

Chrome调试里的FormData 和 Request Payload 有什么不同

最近注意到 Chrome 的开发工具里有时这个地方有时显示的是 Request Payload,有时显示的是 FormData.

刚开始我以为可能只是 Chrome 的一个显示 bug 之类的,也没有发现有什么规律.后来百度一下才发现里面还是有些门道的. 我在思否的这篇文章里找到了答案,这篇文章里的答案也是从 StackOverflow 上贴过去的. 原问题和回答如下:

What’s the difference between “Request Payload” vs “Form Data” as seen in Chrome dev tools Network tab? The Request Payload - or to be more precise: payload body of a HTTP Request - is the data normally send by a POST or PUT Request. It’s the part after the headers and the CRLF of a HTTP Request. A request with Content-Type: application/json may look like this:

1
2
3
4
POST /some-path HTTP/1.1
Content-Type: application/json

{ "foo" : "bar", "name" : "John" }

If you submit this per AJAX the browser simply shows you what it is submitting as payload body. That’s all it can do because it has no idea where the data is coming from. If you submit a HTML-Form with method=”POST” and Content-Type: application/x-www-form-urlencoded or Content-Type: multipart/form-data your request may look like this:

1
2
3
4
POST /some-path HTTP/1.1
Content-Type: application/x-www-form-urlencoded

foo=bar&name=John

In this case the form-data is the request payload. Here the Browser knows more: it knows that bar is the value of the input-field foo of the submitted form. And that’s what it is showing to you. So, they differ in the Content-Type but not in the way data is submitted. In both cases the data is in the message-body. And Chrome distinguishes how the data is presented to you in the Developer Tools. 所以 chrome 显示 Request Payload 或者 FormData 的原因就在于 Content-Type 请求头设置的不同.

Content-Type

Content-Type 实体头部用于指示资源的 MIME 类型(media type)

常见的几种 Content-Type

  • aplication/x-www-form-urlencode (原生form表单默认提交数据的格式,form表单数据被编码成key/value 格式发送到服务器)
  • multipart/form-data (表单上传文件时使用此格式)
  • application/json (axios 传递对象默认,JSON数据格式)
  • text/html (HTML格式)
  • text/plain (纯文本格式)

不同请求方式默认 Content-Type 的差异

  • 使用原生 AJAX 方式发送请求,Content-Type 默认为 text/plain
  • 使用原生 Form 表单形式发送请求,Content-Type 默认为 application/x-www-form-urlencode
  • 使用 axios 传递对象时,Content-Type 默认为 application/json
  • 使用 axios 传递字符串形如key1=value1&key2=value2时,默认为 application/x-www-form-urlencode

参考链接:

  1. 前后端联调之Form Data 与 Request Payload,你真的了解吗?

  2. https://www.cnblogs.com/klb561/p/10090540.html