uni.request直接发送formData格式参数,后端接收为空——解决办法
情景描述: Form表单用的是<uni-form> 组件,提交表单是按uni-form的文档调用的
methods: {
submitForm(form) {
// 手动提交表单
this.$refs.form.submit().then((res)=>{
console.log('表单返回得值:', res)
})
}
}
来获取 表单信息res,然后调用uni.request对后端进行请求。写的时候,前几个data传值时,由于参数就一两个,就直接是data:{name:name,pwd:pwd},
写的,后来这个表单涉及到data传值较多,打算直接data:res,
就完了,让后端自己接收去呗。但一测试,报500,传值为空。。。
. 就很纳闷,表单的参数名都对应着呢,又把后端改成map接收也不行,前端console.log('表单的值:', res)
控制台也是有值的。
解决办法
通过参看前端控制台发现,uni.request默认请求头是content-type:application/json,而我并没有对请求头进行设置,
网上查了一下,对请求头设置了一下
this.$refs[form]
.submit()
.then(res => {
console.log('表单的值:', res)
uni.request({
url: 'url',
method: 'POST',
data: res,
header: {
"Content-Type": "application/x-www-form-urlencoded"
}, // 请求头,使参数可以formData格式发送
dataType: 'json', // 返回数据格式,
success: result => {
if (success) {
console.log(result);
uni.showToast({
title: '验证失败,'+error,
image: '/static/img/error.png'
})
} else {
uni.showToast({
title: '验证成功'
})
}
},
});
})
.catch(errors => {
console.error('验证失败:', errors)
})
将Content-Type设置成application/x-www-form-urlencoded后,后端成功接受到各参数,问题解决。
/
4.28更新
后来测试中,了解到还有另一种解决方法
给后端参数前加一个@RequestBody
@RequestMapping("aMethods")
public JsonBean aMethods(@RequestBody UserInfo userInfo){
return aService.aServiceMethod(userInfo);
}
就解决了
。
起因是因为有个Integer类型的参数传空值时,后端接收判类型转换错误;
后来也给后端接参也加了@RequestBody这个,再测试,还是不行,是因为前端请求头还是用的之前的
"Content-Type": "application/x-www-form-urlencoded"
也就是说,加@RequestBody后,前端请求头得是
"Content-Type": "application/json"
了。