前言
本节学习小程序的http请求,为此,先用springboot搭建一个后台(包含连接mysql)。
1 新建springboot项目
1)打开IDEA,New Project -> Spring Initializr
2)点击next,修改包名
2)点击next,选择web -> Spring Web
3)点击next,修改项目名称,finish
2 连接Mysql数据库
1)打开pom.xml,添加依赖 ( lombok 通过注解方式,简化java代码)
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
2)maven -> install,maven -> Reimport
3)创建本地mysql数据库的过程略过,添加一条数据
4)打开application.properties,添加数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/wx-demo?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
3 增加获取数据接口
1)新建UserInfoController.java
@RequestMapping(value = "/info", method = {RequestMethod.GET, RequestMethod.POST})
public ResponseMessage<UserInfo> getUserInfo(@RequestBody JSONObject jsonObject) {
int id = jsonObject.getInteger("id");
UserInfo info = infoService.selectUserInfoById(id);
return apiResultMap("查询成功", info);
}
2)其他内容无详述必要,参见源代码,运行后台
mvn spring-boot:run
4 发送请求
1)开发者工具,详情->本地设置,勾选不校验域名
2)打开index.js,新增函数selectInfo
selectInfo: function(e) {
var that = this;
wx.request({
url: "http://localhost:8080/user/info",
method: "POST",
data: {
id: e.currentTarget.dataset.id
},
success: function (res) {
console.log(res)
that.setData({
id: res.data.data.id,
userName: res.data.data.userName,
sign: res.data.data.sign
});
},
fail: function (res) { },
complete: function (res) { },
})
}
})
3)打开index.wxml,绑定事件
<view>
<button bindtap="selectInfo" data-id="1">获取用户信息</button>
<view>id:{{id}}</view>
<view>昵称:{{userName}}</view>
<view>签名:{{sign}}</view>
</view>
4)点击按钮,效果如下