What is the difference between request payload and formData in HTTP request?

What is the difference between request payload and formData in HTTP request?

FormData and Payload are the two formats that the browser transmits to the interface. These two methods are distinguished by Content-Type ( understand Content-Type ). If it is application/x-www-form-urlencoded, then It is the formdata method, and if it is application/json or multipart/form-data, it is the request payload
method .
For example, the code for submitting a post request using the ajax method is as follows (application/x-www-form-urlencoded encoding is used by default):

<!DOCTYPE html>
<html>
<head>
  <title></title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0">
  <script type="text/javascript" src="https://tugenhua0707.github.io/html5UploadImage/js/jquery.js"></script>
</head>
<body>
  <div id="app">
    <div class="btn">发送post请求</div>
  </div>
  <script>
    var obj = {
      "name": 'CntChen',
      "info": 'Front-End',
    };
    $('.btn').click(function() {
      $.ajax({
        url: ' www.example.com ' ,
        type: 'POST',
        dataType: 'json',
        data: obj,
        success: function(d) {
          
        }
      })
    });
  </script>
</body>
</html>

As shown below:

2. Upload files using the multipart/form-data form

The following html code:

<!DOCTYPE html>
<html>
<head>
  <title></title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0">
</head>
<body>
  <div id="app">
    <form action="http://www.example.com" method="POST" enctype="multipart/form-data">
      <p>username: <input type="text" name="fname" /></p>
      <p>age: <input type="text" name="age" /></p>
      <input type="submit" value="提交" />
    </form>
  </div>
</body>
</html>

As shown below:

 

You can see that the Request Payload format is used when uploading files using the multipart/form-data form;

3. Use Content-Type: application/json to encode

The following html code:

<!DOCTYPE html>
<html>
<head>
  <title></title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0">
  <script type="text/javascript" src="https://tugenhua0707.github.io/html5UploadImage/js/jquery.js"></script>
</head>
<body>
  <div id = "app" > 
    < div class = "btn" > send post request </ div > 
  </ div >

  <script>
    $('.btn').click(function() {
      $.ajax({
        url: 'http://localhost:8081/api.json',
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify({a: [{b:1, a:1}]}),
        success: function(d) {
          
        }
      })
    });
  </script>
</body>
</html>

As shown below

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325205601&siteId=291194637