关于小程序提交Post请求给后端,后端没有收到数据的情况
问题描述
小程序发送post请求,请求头中包含装填的数据信息,但是后端并没有实现应有的数据接收效果。
我使用的是SpringBoot的参数对象封装,但是请求发送后打印出来的对象都是null,并没有将数据封装为一个对象。
解决办法
小程序端发送数据请求的时候设置请求头格式为:
'content-type': 'application/x-www-form-urlencoded'
。补充一句,我之前的格式是
"Content-Type": "application/json"
具体代码
小程序端
//请求 request({ url: '/user/wx/user/updateLocation', method: "post", data:{ "latitude":that.data.markers[0].latitude, "longitude":that.data.markers[0].longitude, 'userFace':userInfo.avatarUrl, 'nickName':userInfo.nickName }, }).then((res)=>{ console.log(res); }) //请求工具类。另行文件编写 export const request=(params)=>{ //定义公共的url const baseUrl="http://localhost:8888/xxxx" return new Promise((resolve,reject)=>{ console.log(params); wx.request({ ...params, url: baseUrl+params.url, header: params.header || { 'content-type': 'application/x-www-form-urlencoded', 'token':wx.getStorageSync('token'), 'openid':wx.getStorageSync('openid') }, success:(result)=>{ resolve(result); }, fail:(err)=>{ reject(err); }, complete:()=>{ } }); }) }
后端数据代码
@ApiOperation(value = "登录后修改更新用户位置信息") @PostMapping("/wx/user/updateLocation") public ResponseBean updateLocation(User user,HttpServletRequest request){ String openid = request.getHeader("openid"); System.out.println(user); user.setOpenId(openid); userService.updateLocation(user); return responseBean.setMessage("更新成功").setData(200); }
实现效果
自定义的对象能够赋值并打印
拓展
Content-Type
(MediaType),即是Internet Media Type,互联网媒体类型,也叫做MIME类型 . 在HTTP协议消息头中,使用Content-Type来表示请求和响应中的媒体类型信息。常见的Content-Type
application/x-www-form-urlencoded
:最常见的Post提交数据的形式,一般用来提交表单。数据被编码成 名称/值对 ,即 key1=value1&key2=value2 形式。application/json
:轻量级数据格式,以键值对方式组织数据。使用该类型时参数本身就是Json格式,且参数会被直接放入请求体中,不做任何处理。multipart/form-data
:是支持文件上传的样式,一般上传文件的表单才用此类型。