uni.request POST 请求后台接收不到参数
问题描述
前端用uni.reauest
发送POST
请求,后台接收不到参数。
原因分析
是因为uni.request
对传入data
数据转换后,后台接收数据形式没有对应上。
uniapp 官网对data
的说明:
默认的content-type
:
也就是说,当method
为POST
,并且header
为application/json
时,data
会被序列化为 JSON 字符串,所以这个时候,后台需要用一个对应的封装好的实体类或者Map
配合注解@RequestBody
接收。
前端请求,method
为POST
且content-type
默认,即application/josn
:
uni.request({url: 'http://localhost:8080/login/wxLogin',method: 'POST',data: {code},success: (res) => {console.log(res)}})
后端需要用@RequestBod Map<String, String>
接收:
@PostMapping("/wxLogin")public RespBean wxLogin(@RequestBody Map<String, String> map) {System.out.println("code: " + map.get("code"));return RespBean.ok("成功");}
解决办法
如果不想像上面那样用 map 接收,可以修改uni.request
的header
为'content-type': 'application/x-www-form-urlencoded'
。
前端请求:
uni.request({url: 'http://localhost:8080/login/wxLogin',method: 'POST',header: {'content-type': 'application/x-www-form-urlencoded'},data: {code},success: (res) => {console.log(res)}})
后端直接接收:
@PostMapping("/wxLogin")public RespBean wxLogin(String code) {System.out.println("code: " + code);return RespBean.ok("成功");}
如果觉得《uni.request POST 请求后台接收不到参数》对你有帮助,请点赞、收藏,并留下你的观点哦!