微信小程序 雲函數訪問 Http

微信小程序正式版無法正常調用http類型的API接口,只有htttps類型纔可以通過驗證,利用雲函數可以避免這一難點。下面我會給出一個小案例。

1.前端頁面-----index.js

Page({

  /**
   * 頁面的初始數據
   */
  data: {

  },
  history() {
    console.log(666666666)

    //調用雲函數
    wx.cloud.callFunction({

      // 雲函數名稱
      name: 'HttpApi',
      // 傳給雲函數的參數
      data: {},
      success: function(res) {
        console.log(res.result)

        //將返回的值轉爲json格式
        var p = JSON.parse(res.result)
        console.log(p)
        console.log(p.result)
        // var that = this;
        // that.setData({
        // })
      },
      fail: console.error
    })

  }
})

1.雲函數HttpApi-----index.js

使用雲函數前安裝這個命令:npm install request-promise

//npm install  request-promise   先安裝這個命令
var API_URL = "http://api.juheapi.com/japi/toh?key=******************&v=1.0&month=11&day=1"

// 雲函數入口文件
const cloud = require('wx-server-sdk')

var rp = require('request-promise');
cloud.init()

// 雲函數入口函數
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let url = API_URL;
  return await rp(url)
    .then(function (res) {
      return res
    })
    .catch(function (err) {
      return '失敗'
    });
}
//==扣扣羣聊172842597==```
![在這裏插入圖片描述](https://img-blog.csdnimg.cn/20191226214233244.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3p4Nzc1ODgwMjM=,size_16,color_FFFFFF,t_70)

![在這裏插入圖片描述](https://img-blog.csdnimg.cn/2019122621452262.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3p4Nzc1ODgwMjM=,size_16,color_FFFFFF,t_70)




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