云函数
小程序云函数的运行环境为node.js首先安装node环境
node安装
https://blog.youkuaiyun.com/qq_37164093/article/details/89960761
获取淘宝镜像https://npm.taobao.org/mirrors/ 找到node.js下载
或使用命令
npm install node
node -v 可查看版本
新建云函数
cloudfunctions 右键新建云函数
如果提示缺少wx-server-sdk 安装就好了
如果是在调用的时候提示需要安装则在cloudefunction右键选择在终端中打开 输入命令
npm install --save wx-server-sdk@latest
- 例如求和函数
云函数定义
// 云函数入口函数
exports.main = async (event, context) => {
//定义异步函数async
//event包括我们调用云函数时小程序段传过来的参数
//context当前调用的上下文也包含一些用户的信息
return {
sum: event.a + event.b
}
}
小程序端调用
sum: function(){
wx.cloud.callFunction(
{
name: 'sum',
data:{
a:2,
b:3
}
}
).then(res=>{
console.log(res);
}).catch(err=>{
console.log(err);
});
},
- 删除函数实现
小程序端利用doc函数输入id只能获取一个对象的引用如果想成批删除数据那么就需要云函数来实现
在云端新建云函数
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database();
// 云函数入口函数
exports.main = async (event, context) => {
try{
return await db.collection('user').where({
name: event.name
}).remove();
} catch(e){
console.error(e);
}
}
小程序端调用
nameDelete:function(){
wx.cloud.callFunction(
{
name:'selectdelete',
data:{
name:'jerry'
}
}
).then(res=>{
console.log(res);
}).catch(err=>{
console.log(err);
}
)
},