实战——使用云函数(一)小程序与云函数的参数传递
发布于 2 年前 作者 yang93 4530 次浏览 来自 分享

建立环境

首先需要在project.config.json 文件,新增 cloudfunctionRoot 字段
{
“cloudfunctionRoot”: “cloudfunctions/”
}
接着:右键当前环境,选择新建 Node.js 函数,这里我们将云函数命名为 todo_functions

可以看到其内部有一个模板
// 云函数入口文件
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,
  }
}

其中上面的 exports.main = async (event, context) 中event 对象中含有——调用时传输的参数、openid、appid

小程序中调用云函数

如何在js中调用云函数:

wx.cloud.callFunction({
  // 云函数名称
  name: 'todo_functions', 
  // 传给云函数的参数
  data: {
	name:"world !!!"
  },
  success: function(res) {
    console.log(res.result.new_name) // hello world !!!
  },
  fail: console.error
})

云函数中的接收参数

在云函数中接收js传来的参数,并返回参数:

exports.main = async (event, context) => {
  return {
    new_name: "hello " + event.name  // 接收来自js的参数name,返回新的返回值new_name
  }
}

记得写好云函数后,要记得上传哦!(右键函数,选择上传并部署:云端安装依赖)

总结

好了,到现在的我们,我们完成了云函数与小程序的参数传递,小程序调用函数wx.cloud.callFunction,把参数 name 写道data中,将数据传到云函数 todo_functions,接着云函数通过event接收到来在小程序的参数,event.name可以获取到参数,接着小程序通过success,可以接收到云函数成功调用后返回的new_name, res.result.new_name。

1 回复

正好在学云开发,感觉有所帮助

回到顶部