云函数
云函数请求HTTP
- 请求的http地址不需要备案,也可以不是https
异步返回结果
不会阻塞原进程
// index.js
exports.main = async (event, context) => {
return new Promise((resolve, reject) => {
// 在 3 秒后返回结果给调用方(小程序 / 其他云函数)
setTimeout(() => {
resolve(event.a + event.b)
}, 3000)
})
}
流程
编写云函数
- 新建:cloudfunctions -> 右键点击
- 例:
其中云函数入口参数是一个json Object,在调用云函数时传入
return 返回一个 json object,在调用云函数后通过 res.result.* 访问
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV
})
// 云函数入口函数
exports.main = async (event, context) => {
const wxContext = cloud.getWXContext()
return {
event,
openid: wxContext.OPENID,
appid: wxContext.APPID,
product: event.a * event.b,
}
}
环境配置步骤
- 设置环境,cloudfunctions -> 右键点击
- 配置 node.js 和wx-server-sdk
- 安装 node.js, 将 \nodejs\node_modules\npm\bin添加到环境变量
- 在指定云函数目录下打开终端(也就是每个云函数都要这么弄一次)
npm install --save wx-server-sdk@latest
- 云函数目录右键点击 -> 上传并部署所有文件, 重新编译
调用云函数
示例:
multiFunction:function(eve){
console.log('yes')
wx.cloud.callFunction({
name:'multi',
data:{
a:this.data.a,
b:this.data.b
},
success:res=>{
this.setData({
result: JSON.stringify(res.result.product)
})
console.log("appid:"+res.result.appid)
console.log("openid:"+res.result.openid)
console.log("event:"+res.result.event)
},
fail: err => {
wx.showToast({
icon: 'none',
title: '调用失败',
})
console.error('[云函数] [sum] 调用失败:', err)
}
})
},
数据库
权限
dGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxOTU2ODYw,size_16,color_FFFFFF,t_70)
watch
const db = wx.cloud.database()
watcher = db.collection('todos').where({
team: 'our dev team'
}).watch({
onChange: function (snapshot) {
console.log('docs\'s changed events', snapshot.docChanges)
console.log('query result snapshot after the event', snapshot.docs)
console.log('is init data', snapshot.type === 'init')
},
onError: function (err) {
console.error('the watch closed because of error', err)
}
})
...
watcher.close()
查询操作
- SELECT * FROM books where name=‘战争史’
const db = wx.cloud.database();
db.collection('books').where({
name:"战争史"
}).get({
success:function(res){
console.log(res)
}
})
技巧
- 可以在console中直接测试云函数
wx.cloud.callFunction({name:'msgMe', data:{taskId:'7c47f3615dccd172004615de62bb9908', formId:'this'}}).then(console.log)
坑
- 云函数上传时不会自动保存
所以上次之前线ctrlS,否则上传的不是自己最新修改的 - loud function service error code -504002, error message Cannot read property ‘_id’ of undefined;
错误代码:
mtask = todos.doc(event.taskId).get();
return mtask.data;
.get()获取时采用的异步的方式,所以后面mtask.data 为null
改正:mtask = await todos.doc(event.taskId).get();
-
数据库权限不对导致没有得到数据
-
Cannot find module 'wx-server-sdk’
npm install --save wx-server-sdk@latest