小程序之HTTP请求

前言

本节学习小程序的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)点击按钮,效果如下
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值