有勇气的牛排博客
☰

微信小程序通过云函数请求http网站接口


知止自律打卡-微信小程序APP
一款微信自律打卡小程序,支持自定义打卡项目、习惯记录、项目日记、专注计时与数据统计。自律打卡、学习打卡、读书打卡、健身打卡、运动打卡、减肥打卡、戒色打卡、养生打卡、戒烟、戒酒、戒熬夜等多种场景。万能打卡模板自由创建。可自定义每日打卡目标,记录习惯连续天数,可视化追踪成长进度。
了解产品详情 →
微信搜索「知止自律打卡」
知止自律打卡微信小程序

1 介绍

微信小程序正式版无法调用http类型的API接口,只有htttps类型才可以通过验证,可以利用云函数避免这一难点。下面我会给出一个小案例。

2 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
    })

  }
})

3 云函数 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 '失败'
    });
}

json数据

文件目录

标签:

×
×