RequestPayload和Formdata

今天使用fecth作异步的服务获取,调用方法以下jquery

return xFetch('/api/common/getsearchowner.json',{body: JSON.stringify(para),method:'POST'});

查看前台发出的request以下ajax

POST /api/common/getsearchowner.json HTTP/1.1
Host: localhost:8989
Connection: keep-alive
Content-Length: 11
Pragma: no-cache
Cache-Control: no-cache
authorization:
Origin: http://localhost:8989
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36
content-type: text/plain;charset=UTF-8
Accept: */*
Referer: http://localhost:8989/
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.8,en;q=0.6

且有一个request payload的值json

{"aaa":111}

而之前使用ajax的时候彷佛没有这个值,而是一个form data记录了post的值api

csrftoken:1472039431885

formdata和requestpayload到底有什么区别呢、为何用fecth的时候,提交的数据都变成了request payload?服务器

对于get请求,表单参数以name=value&name1=value1的形式附到url的后面app

对于post请求,表单参数是在请求体中,也是以name=value&name1=value1的形式在请求体中,而且post请求的Content-Type为application/x-www-form-urlencoded,参数是在请求体中,即请求中的Form Data。在servlet中,能够经过request.getParameter(name)的形式来获取表单参数。异步

可是若是是原生的ajax请求,请求的Content-Type为text/plain;charset=UTF-8,而请求表单参数在RequestPayload中。此时的POST请求是不会读取请求体数据和进行相应的参数处理的,即不会解析表单数据来放到request parameter map中。因此经过request.getParameter(name)是获取不到的。此时servelet中只能用解析流的解析post

为何原生的ajax后者fetch不能获取form data呢?fetch

jquery在执行post请求时,会设置Content-Type为application/x-www-form-urlencoded,因此服务器可以正确解析,而使用原生ajax请求时,若是不显示的设置Content-Type,那么默认是text/plain,这时服务器就不知道怎么解析数据了,因此才只能经过获取原始数据流的方式来进行解析请求数据。url

解决方案是什么呢?能够再请求的时候增长

headers: {'Content-Type': 'application/x-www-form-urlencoded'}

参考文档:http://stackoverflow.com/questions/10494574/what-is-the-difference-between-form-data-and-request-payload

http://blog.csdn.net/mhmyqn/article/details/25561535

相关文章
相关标签/搜索