赞
踩
问题描述:最近在做一个小程序,后端用的java。在使用wx.request 来传递参数的过程中发现后端不能成功接收传递的参数。
代码
小程序端代码如下
- wx.request({
- url: 'http://localhost:8080/project/phonePassword',
- method:"POST",
- data:{
- "phone":phone,
- "password":password
- },
- header: {
- 'content-type': 'application/json'//默认值
- },
- success (res) {
- console.log(res.data)
- }
- })
java控制器代码如下
- @PostMapping("/phone/phonePassword")
- @ResponseBody
- public BuildUser getByUserId(@RequestParam String password,@RequestParam String phone){
- return buildUserService.getByPhonePossword(phone,password);
- }
结果发现报错
Required String parameter 'possword' is not present
查阅资料发现问题所在
在http请求中content-type 来确定请求的媒体类型(格式)
1.当content-type的值为application/x-www-form-urlencoded时
浏览器的原生 <form> 表单,其中ajax也是用这种方式提交的
这种情况下可以使用@RequestParam, @ModelAttribute处理,当然@RequestBody也能处理
2.当content-type的值为multipart/form-data时
表单上传文件用的这种提交方式
不能处理,使用@RequestBody注解也不能处理。
3.当content-type的值为application/json或者application/xml
这种提交方式的消息主体是一个json字符串
只能使用@RequestBody注解来处理这种参数。
解决方式
1.第一种解决方式改变小程序wx.request请求头中的content-type类型,值改为application/x-www-form-urlencoded
- wx.request({
- url: 'http://localhost:8080/partybuild/buildUser/phone/phonePossword',
- method:"POST",
- data:{
- "phone":phone,
- "possword":possword
- },
- header: {
- 'content-type': 'application/x-www-form-urlencoded'
- },
- success (res) {
- console.log(res.data)
- }
- })
2.第二种方式 是 Controller 用@RequestBody 接收参数,小程序还是’content-type’: 'application/json’不变,
- @PostMapping("/phone/phonePassword")
- @ResponseBody
- public BuildUser getByUserId(@RequestBody Map<String, String> req){
- return buildUserService.getByPhonePossword(req.get("phone"),req.get("password"));
- }
原文链接http://www.jhone.top/index/index/toread.html?article_id=11
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。