formData和request Payload

发布时间 2023-03-31 22:44:37作者: 1769987233
Form Data
Post表单请求
代码示例
headers = {
	"Content-Type": "application/x-www-form-urlencoded"
}
requests.post(url, data=data, headers=headers)

  
 
Request Payload
传递json数据
headers = {
	"Content-Type": "application/json"
}
requests.post(url, data=json.dumps(data), headers=headers)


二者区别
如果一个请求的Content-Type设置为application/x-www-form-urlencoded,那么这个Post请求会被认为是Http Post表单请求,那么请求主体将以一个标准的键值对和&的querystring形式出现。这种方式是HTML表单的默认设置,所以在过去这种方式更加常见。
其他形式的POST请求,是放到 Request payload 中(现在是为了方便阅读,使用了Json这样的数据格式),请求的Content-Type设置为application/json;charset=UTF-8或者不指定。

在http的请求中,formData和request Payload常出现于POST请求中,比如正常的ajax post请求中:

$.ajax({
    url:'/index',
    type:'post',
    dataType:'json',
    data:{
        name:'acc',
        age:13
    },
    success:res => {
        
    }
})

此时这个请求发出去后,它的content-type: application/x-www-form-urlencoded,而且这是一个默认参数,form表单的默认情况下,其enctype也是设置为此属性。在请求头的底部,你也可以看到发送的参数出现在FromData中。
如果我们把上面的代码改一下:
$.ajax({
    url:'/index',
    type:'post',
    dataType:'json',
    contentType: 'application/json',
    data:{
        name:'acc',
        age:13
    },
    success:res => {
        
    }
})

此时这个请求发出去后,它的content-type: application/json,在请求头的底部,你也可以看到发送的参数出现在Request Payload中。
除此之外,最近的新request Fetch API也能做到这一点。

var data = { 'name': 'pdd', 'password': 19 }
fetch('/post', {
     method: 'post',
     headers: new Headers({
            'Content-Type': 'application/json'
     }),
     body: JSON.stringify(data)
}).then(res => res.text())
  .then(res => {
        console.log('post-data', res);
  })