问题描述
最近在做微信小程序,用的spring boot做后端,突然发现客户端发送post请求的时候服务端接收不到参数。问题简化之后如下:
微信小程序端:
在页面放一个按钮进行测试
绑定一个函数发送post请求
//index.js
//获取应用实例
const app = getApp()
Page({
testpost:function(){
wx.request({
url: 'http://127.0.0.1:8081/testpost/demo',
method:'POST',
data:{
name:'lijing',
age:'18'
},
success:function(res){
console.log(res);
},
fail:function(err){
console.log(err)
}
})
}
})
如图所示:
服务端
服务端新建一个springBoot项目,配置端口和路径
server.port=8081 server.servlet.context-path=/testpost
再新建一个controller用于测试:
package com.demo.demo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@RequestMapping(value = "/demo",method = RequestMethod.POST)
public String demo(String name,String age){
System.out.println("name = [" + name + "], age = [" + age + "]");
return "server response";
}
}
可见,如果能获取到参数的话就会在控制台打印参数。
但是在小程序界面点击按钮之后,服务端并不能获取到数据,如下:
解决方法
查阅资料之后发现,post请求提交数据有四种常见方式:
application/x-www-form-urlencoded
浏览器的原生



