微信小程序 云函数访问 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)




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