微信小程序云开发-云函数使用
2020-03-30 本文已影响0人
月圆星繁
获取用户openid
- 创建云函数 getopenid(名字可以随便定义)文件夹,在index.js中默认有函数
// 云函数入口文件
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,
}
}
- 使用云函数, 在index.js页面定义方法getopenid(方法名可以随便定义)
Page({
// 使用云函数
getopenid:() => {
wx.cloud.callFunction({
name:'getopenid',
success: res => {
console.log("openid: ",res.result.openid)
}
})
}
})
云函数获取数据库数据
- 创建云函数目录,编写代码之后,要部署
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
// 云函数入口函数
exports.main = async (event, context) => {
return cloud.database().collection('users').get()
}
- 获取数据
Page({
// 使用云函数
getDataByYun: () => {
wx.cloud.callFunction({
name:'yungetdata',
success: res=>{
console.log('数据库数据', res);
},fail: res=> {
console.log('数据库数据获取失败', res);
}
})
}
})
云函数获取和数据库api获取云数据库数据的时候,最大的区别是权限问题,云函数的获取权限能力更大