微信小程序与OneNet之间的数据交互 POST、GET数据 invalid JSON

微信小程序在与网站服务器进行数据交互时,会用到wx.request函数,GET表示获取,POST表示上传。

2020年4月14日更新:今天才在官方文档中看到下面消息 

       

1、微信小程序上传数据到OneNet服务器时:

method:POST

data参数表示主要上传的数据,注意上传到OneNet的数据必须是json格式,直接上传数据时不能成功的,会返回错误信息:invalid JSON。  需要用到JSON.stringify函数将数据转化为json格式,此处花了3个多小时才找出问题所在。

header:网页访问请求的头部,需添加"content-type":'application/x-www-form-urlencoded'

示例程序如下:

OneNet_Post:function(){
    var that=this
    let deviceid = "5*****819"
    let apikey = "5L8***************9o="
    let data={
      "datastreams": [
        {"id": "temp1","datapoints":[{"value": that.data.temp1}]},
        {"id": "temp2","datapoints":[{"value": that.data.temp1-1}]},
      ]
    }
    wx.request({
      url: "https://api.heclouds.com/devices/" + deviceid + "/datapoints",
      method:'POST',
      header:{
        "content-type": 'application/json',
        "api-key": apikey
      },
      data:JSON.stringify(data),
      success(res){
        console.log("更新数据成功",res)
      },
      fail: function(res){
        wx.showToast({ title: '系统错误' })
      },
      complete:function(res){
        wx.hideLoading()
      }
    })
  },

1、微信小程序从OneNet服务器获取数据时:

method:GET

data:可以没有此参数

header:网页访问请求的头部,需添加"content-type":'application/x-www-form-urlencoded'

示例程序如下:

OneNet_Get: function(){
    var that=this
    let deviceid = "5******9"
    let apikey = "5****************="
    wx.request({
      url: "https://api.heclouds.com/devices/" + deviceid + "/datastreams",
      method:'GET',
      header:{
        "content-type": 'application/x-www-form-urlencoded',
        "api-key": apikey
      },
      success(res){
        console.log(res)
        if(res.statusCode === 200){
          that.setData({
            temp1: res.data.data[1].current_value,
            temp2: res.data.data[2].current_value,
          })
        }
      },
      fail: function(res){
        wx.showToast({ title: '系统错误' })
      },
      complete:function(res){
        wx.hideLoading()
      }
    })
  },

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章