Skip to content
On this page

创建云函数

cloud文件夹 右键 新建node.js云函数,会生成config.json,index.js,package.json三个文件 index.js长这样

typescript
// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  return {
    event,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  }
}

需要数据库这样写

typescript
// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    return await db.collection('logs').add({
      data: {
        add: event.add,
        date: event.date,
        openid:event.openid
      }
    })
  } catch (e) {
    console.log(e)
  }
}

·

使用云函数

app.json初始化(引入)

typescript
App({
  onLaunch: function () {
    wx.cloud.init({
      env: "test-r8e3o",// 云开发环境id
      traceUser: true
    })
  }
})

用到页面对应的js

typescript
// 云函数调用
let that = this
wx.cloud.callFunction({
  name: "login",
  success: res => {
    console.log('云函数login调用成功')
    console.log(e, res)
    that.setData({
      hasUserInfo: true,
      // userInfo: e.detail.userInfo,
      openid: res.result.openid
    })
    that.data.userInfo.openid = that.data.openid
  },
  fail: res => {
    console.log('云函数login调用失败')
  }
})

粤ICP备2024285819号