微信小程序與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()
      }
    })
  },

 

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