What does it mean http request body?

后端 未结 3 726
感情败类
感情败类 2020-12-23 17:13

Upon reading stuffs about POST and get methods here there is a statement like \" when used post method it uses HTTP request Body . What Does it mean \" HTTP request body\".?

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-23 18:12

    The following html

    :

    
      
      
      
      
    
    

    will send this HTTP request (which is a type of HTTP message):

    POST / HTTP/1.1
    Host: localhost:8000
    User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:50.0) Gecko/20100101 Firefox/50.0
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    Accept-Language: en-US,en;q=0.5
    Accept-Encoding: gzip, deflate
    Connection: keep-alive
    Upgrade-Insecure-Requests: 1
    Content-Type: multipart/form-data; boundary=---------------------------8721656041911415653955004498
    Content-Length: 465
    
    -----------------------------8721656041911415653955004498
    Content-Disposition: form-data; name="myTextField"
    
    Test
    -----------------------------8721656041911415653955004498
    Content-Disposition: form-data; name="myCheckBox"
    
    on
    -----------------------------8721656041911415653955004498
    Content-Disposition: form-data; name="myFile"; filename="test.txt"
    Content-Type: text/plain
    
    Simple file.
    -----------------------------8721656041911415653955004498--
    

    Lines POST / HTTP/1.1 to Content-Length: 465 are the HTTP headers, whilst the rest -- following the empty line -- corresponds to the HTTP message body (also known as content).

    So how do you access this data in the back-end/server-side?
    Different server-languages (e.g. Go-lang, Node.js and PHP... etc) have different ways to parse the http body from a http post request. In Node.js it is common to use body-parser which is a parsing middleware function (see example below).

    // Node.js
    // OBSERVE THAT YOU NEED THE BODY-PARSER MIDDLEWARE IN ORDER TO DO THIS!
    ⋮
    var data1 = req.body.myTextField;
    var data2 = req.body.myCheckBox;
    var data3 = req.body.myFile;
    ⋮
    

    More information about bodies:

    Bodies can be broadly divided into two categories:

    1. Single-resource bodies, consisting of one single file, defined by the two headers: Content-Type and Content-Length.
    2. Multiple-resource bodies, consisting of a multipart body, each containing a different bit of information. This is typically associated with HTML Forms.

    Sources:

    • MDN

提交回复
热议问题