云函数的使用与环境配置:
1、创建云函数
右键cloudfunctions文件选择新建Node.js云函数,云函数命名为updateVoice用于修改用户语音数量。

2、安装node.js及npm:
一:从Node.js官网下载对应平台的安装程序
二:一键安装
三:打开cmd,输入node -v,npm -v如果出现版本号,证明安装成功
注意:在使用npm可能会出现“npm不是内部或外部命名,与不是可运行程序”的提示,这是由于环境变量问题,需对node进行环境变量配置。
3、安装wx-server-sdk
右键updataVoice在终端中打开,运行:
npm install --save wx-server-sdk@latest


安装成功后云函数文件夹中会有多一个文件(package-lock.json):

右键上传并部署:所有文件

打开云端控制台可以看到我们云函数中已经有一个云函数了。

在云函数updateVoice下index.js进行云函数代码编写:
console.log("4")
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
//声明数据库
const db = cloud.database()
console.log("3")
// 云函数入口函数
exports.main = async (event, context) => {
console.log("2")
//取得传过来的参数
var voice = event.voice, openId = event.openId;
//云函数,更新
try {
return await db.collection('users').where({
_openid: openId
}).update({
data: {
voice: voice
},
success: res => {
console.log('云函数成功')
},
fail: e => {
console.error(e)
}
})
} catch (e) {
console.error(e)
}
}
网友评论