• HTTP请求之 Request Payload 和 Form Data


    【转载】 https://segmentfault.com/a/1190000018774494

    stackoverflow 上高票回答

    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:

    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:

    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.

    所以区别就是,他们只是因为Content-Type设置的不同,并不是数据提交方式的不同,这两种提交都会将数据放在message-body中。但是chrome浏览器的开发者工具会根据这个ContentType区分显示方式。

    注意点

    1.当我们传递字符串的时候,Content-Type自动转为xxx-form-xxx的形式。当为对象的时候,自动转化为xxx/json
    2.字符串的时候以key1=val1&key2=val2的形式体现,对象以JSON字符串形式体现。

    Content-Type的差异

    1.传统的ajax请求时候,Content-Type默认为"文本"类型。
    2.传统的form提交的时候,Content-Type默认为"Form"类型。
    3.axios传递字符串的时候,Content-Type默认为"Form"类型。
    4.axios传递对象的时候,Content-Type默认为"JSON"类型

    后端取不到值?

    无论何种形式传递,后端解析表单信息的时候,会考虑Content-Type。如果是JSON字符串的话,后端解析payload的内容时候,肯定要去解析JSON啦。如果是key1=value1&key2=value2的形式,则需要去分割字符串。

    当然这些事情一般后端使用的框架会去处理,但是框架给后端提供取值接口有可能是不同的,所以前端的小伙伴在处理请求问题时,一定要跟后端小伙伴商量好,是用JSON还是FormData

  • 相关阅读:
    MEF 编程指南(十一):查询 CompositionContainer
    MEF 编程指南(十):重组
    MEF 编程指南(九):部件生命周期
    MEF 编程指南(八):过滤目录
    MEF 编程指南(七):使用目录
    MEF 编程指南(六):导出和元数据
    MEF 编程指南(五):延迟导出
    MEF 编程指南(四):声明导入
    MEF 编程指南(三):声明导出
    MEF 编程指南(二):定义可组合部件和契约
  • 原文地址:https://www.cnblogs.com/it-Ren/p/14884834.html
Copyright © 2020-2023  润新知