uniapp:request 请求出现400错误
开发需求:我们团队在使用 uniapp springboot 开发微信小程序项目,前端向后端发送request 请求时,前端爆出400错误。
400错误: 请求无效 (Bad request);出现这个请求无效报错说明请求没有进入到后端服务里
原因: 前端提交的数据或请求的Url,在后端参数中不能封装或不能处理;前端 uniapp中的uni.request请求中的header 需要编写正确,不然后端拿不到前台的数据,会爆400错误。
解决: 需要注意因为发送的是POST请求,所以需要将请求头设置为 ‘content-type’ : ‘application/x-www-form-urlencoded’ 并将method设置为PSOT类型。
uni.request请求中的header需要编写为:
header: {
"Content-Type": "application/x-www-form-urlencoded"
}
这里header的书写涉及data 数据说明
我们根据最终发送给服务器的数据是否为 String 类型,进行转换,如果传入的 data 不是 String 类型,会被转换成 String。
转换规则如下:
- 对于
GET方法,会将数据转换为 query string。例如{ name: 'name', age: 18 }转换后的结果是name=name&age=18。 - 对于
POST方法且header['content-type']为application/json的数据,会进行 JSON 序列化。 - 对于
POST方法且header['content-type']为application/x-www-form-urlencoded的数据,会将数据转换为 query string。
案例:
uni.request({
url: 'https://www.example.com/request', //仅为示例,并非真实接口地址。
data: {
text: 'uni.request'
},
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
// header: {},设置请求的 header 默认是application/json
success: (res) => {
console.log(res.data);
this.text = 'request success';
}
});
谨以此篇纪念我与bug:400的8h