环境声明
springBoot : 1.8
java : jdk1.8
IDE : IDEAjava
问题描述
axios 表单提交,springBoot 没法接受到数据,但使用swagger测试,能够。ios
缘由
一、axios的表单提交 ,content-type 默认为 application/json;charset=UTF-8
二、提交数据会附加在payload(以JSON形式)。
三、@ModelAttribute 能够接受表单的数据,可是content-type的类型须要为application/x-www-form。@RequestBody 能够接受表单数据,可是content-type类型须要为application/json。@RequestParam 从URL中接受请求参数。(不用于表单提交)。spring
实验json
测试1.1(失败)axios
this.$axios({ url:this.$rootPath+"/category/category", method:'post', data:{ category:this.category } });
public Object inserCategory(@ModelAttribute Category category) {}
http 状态码:app
请求成功,可是服务端没有接受到数据。缘由是@ModelAttribute须要接收FormData形式的数据post
测试1.2(失败)测试
this.$axios({ url:this.$rootPath+"/category/category", method:'post', data:{ category:this.category }, headers:{ 'Content-Type': 'application/x-www-form-urlencoded' } });
public Object inserCategory(@ModelAttribute Category category) {}
http状态码:this
Form Data 被默认组装成了 json的形式,虽然咱们修改了Content-type。url
测试1.3(失败)
if(valid) { this.$axios({ url:this.$rootPath+"/category/category", method:'post', data:{ name: this.category.name, desc: this.category.desc }, headers:{ 'Content-Type': 'application/x-www-form-urlencoded' } });
public Object inserCategory(@ModelAttribute Category category) {}
FormData 仍是json的形式, 不是以FormData的形式。服务端固然接受不到数据
测试1.4(成功)
if(valid) { this.$axios({ url:this.$rootPath+"/category/category", method:'post', data:{ name: this.category.name, desc: this.category.desc }, headers:{ 'Content-Type': 'application/x-www-form-urlencoded' }, transformRequest: [function (data) { return that.$qs.stringify(data); }], });
public Object inserCategory(@ModelAttribute Category category) {}
http状态码:
使用qs对数据在提交前进行了格式化,将其转换成FormData的形式,此时服务端成功接收到数据。
也就是说,使用@ModelAttribute修饰,客户端的content-type须要是 application/x-www-form-urlencoded 且 FormData数据是正确的FormData格式
测试@RequestBody:
测试2.1(失败)
if(valid) { this.$axios({ url:this.$rootPath+"/category/category", method:'post', data:{ name: this.category.name, desc: this.category.desc }, headers:{ 'Content-Type': 'application/x-www-form-urlencoded' }, transformRequest: [function (data) { return that.$qs.stringify(data); }], });
public Object inserCategory(@RequestBody Category category) {}
也就是说@RequstBody 只能支持以JSON数据格式上传。
测试2.2(失败)
this.$axios({ url:this.$rootPath+"/category/category", method:'post', data:{ category:this.category } })
public Object inserCategory(@RequestBody Category category) {}
以这种形式提交数据会失败,由于category在最外面又包装了一个对象。服务端没法正确解析。
测试2.3(成功)
this.$axios({ url:this.$rootPath+"/category/category", method:'post', data:{ name: this.category.name, desc: this.category.desc }, });
public Object inserCategory(@RequestBody Category category) {}
以JSON的形式,将数据上传,服务端成功接受到数据
总结:@RequestBody 只能以json数据提交,数据会负载在Request Payload中;@ModelAttribute 能够以表单数据提交,数据须要以FormData形式提交。
下面是我推荐的写法
this.$axios.post(this.$rootPath+"/category/category",this.$qs.stringify(this.category))
public Object inserCategory(@ModelAttribute Category category) {}
注意:qs 默认会把 content-type 修改成 application/x-www-form-urlencoed。