目录

微信小程序和springboot后台交互,小程序如何传递参数后台如何接收,和一些报错问题

目录

微信小程序和springboot后台交互,小程序如何传递参数后台如何接收,和一些报错问题

总结:

  1. 对于前端发送的json字符串来说,前端使用’Content-type’: ‘application/json’ 这个值是微信小程序默认值。后台使用@RequestBody接收。这样接收的是一个json字符串, 而且必须发post请求

    {"globalData":"{\"nickName\":\"一个好名字\",\"gender\":1,\"language\":\"zh_CN\",\"city\":\"\",\"province\":\"\",\"country\":\"China\",\"avatarUrl\":\"https://thirdwx.qlogo.cn/mmopen/vi_32/ibJ2qdMmNkWhQCspVsvpKGN0052S25In0Kh1CJvJT8Wjc3dHYmOiaR1o7HTM3V2EaJh2xSugM3wic13Ulc4poibKVA/132\"}"}

    可以使用fastjson工具包中的JSONObject对象接收。然后 JSONObject userInfo = lobalData.getJSONObject(“globalData”);获取一个json字符串。userInfo.getString(“nickName”)获取值

  2. 对于发送的普通数据或者对象类型,前端使用’Content-type’: ‘application/x-www-form-urlencoded’ ,在web网页默认为该值。后台使用@RequestParam来接收。

  3. 问题:我在小程序前端传了这些参数。既有普通参数又有json字符串。所以挺懵逼的。再小程序前端Content-type只能设置一种,如果我使用application/x-www-form-urlencoded,则会报 Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported] ,如果使用application/json,会报 Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'openid' is not present] ,发的都是post请求。去网上搜了一下能不能一起使用发现得这样使用却,试了一下确实可以

    wx.request({
              url: "http://127.0.0.1:8080/superadmin/judgecheckresult?scanCode=" + that.data.scanCode,  // 在 url 中传递 String 
              data: JSON.stringify(formData),  // 将 formData 转化成JSON对象
              method: 'POST',
              header: {'Content-Type': 'application/json'},  // http 请求是 JSON 数据格式
              success: function (res) {
                console.log("res")
                console.log(res)
              }
            })
     public String setUserInfo(@RequestParam("openid")String openid
                                    ,@RequestParam("name")String name
    								,@RequestParam("qq")String qq 
    								,@RequestParam("wx")String wx
                                    ,@RequestBody JSONObject lobalData){
    openid: wx.getStorageSync('jiaoxue_OPENID'),
            globalData: JSON.stringify(app.globalData.userInfo),
            name: this.data.name,
            qq: this.data.tel,
            // school: this.data.school,
            // num: this.data.num,
            wx: this.data.year
    //请求模板
    wx.request({
      url: 'test.php', //仅为示例,并非真实的接口地址
      data: {
        x: '',
        y: ''
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success (res) {
        console.log(res.data)
      }
    })

对于后台开发来讲就这个问题你得知道@RequestBody和@RequestParam区别。推荐一个博客

对于微信小程序前后端交互


2021/4/8更新

需求:小程序发送一个数组类型的数据,springboot后台接收

public int addGoodsInCar(@RequestBody JSONObject sums) {
  JSONArray gid = sums.getJSONArray("gid");

这种解决最方便,还有可以写一个实体类,成员是一个数组。接收前端数据时用这个实体接收,感觉挺麻烦。

另外一个问题:前端接收json格式的时间和从数据库查找然后发送给前端的时间相差很大。据查是时区问题。

#在application.properties中加入这个,第二条可以格式化时间
spring.jackson.time-zone=GMT+8
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss