有奖捉虫:云通信与企业服务文档专题,速来> HOT

步骤1:创建目录和云函数文件

1. 在本地创建一个空的文件夹,作为项目的根目录。
2. 进入项目根目录,创建 functions 文件夹。
3. functions 下创建 hello_world 文件夹,包含 index.jspackage.json 两个文件。
此时目录结构如下:
└── functions
└── hello_world
├── index.js
└── package.json
index.js
package.json
exports.main = async function () {
return "Hello World!";
};

{
"name": "hello_world",
"version": "1.0.0",
"main": "index.js"
}

步骤2:发布云函数

命令行工具
小程序开发者工具
2. 项目根目录运行以下命令,并且使用默认配置
cloudbase fn deploy hello_world -e <env-id>
您需要先下载并安装 小程序开发者工具
如果您是首次在微信小程序中使用云开发,请参见 第一个云开发小程序
在微信小程序中首次使用云函数请参看操作指引 我的第一个云函数

步骤3:调用云函数

调用云函数有两种方法:
使用云开发 SDK。

使用 SDK 调用云函数

Web
小程序
Node.js
//初始化SDK实例
const cloudbase = require("@cloudbase/js-sdk");
const app = cloudbase.init({
env: "xxxx-yyy"
});
app
.callFunction({
// 云函数名称
name: "hello_world",
// 传给云函数的参数
data: {
a: 1
}
})
.then((res) => {
console.log(res);
})
.catch(console.error);

wx.cloud
.callFunction({
// 云函数名称
name: "hello_world",
// 传给云函数的参数
data: {
a: 1,
b: 2
}
})
.then((res) => {
console.log(res.result); // 3
})
.catch(console.error);

const cloudbase = require("@cloudbase/node-sdk");
const app = cloudbase.init({
env: "xxxx-yyy"
});
app
.callFunction({
// 云函数名称
name: "hello_world",
// 传给云函数的参数
data: {
a: 1
}
})
.then((res) => {
console.log(res);
})
.catch(console.error);


使用 HTTP 调用云函数

执行以下命令创建一条 HTTP 服务路由,路径为 /hello,指向的云函数为 hello_world
cloudbase service create -p hello -f hello_world -e <env-id>
随后便可以通过 https://<env-id>.service.tcloudbase.com/hello 调用云函数,并获得返回结果。

步骤4(可选):在云函数内使用 Node.js SDK

首先,我们在 functions/hello_world/ 路径下,执行以下命令,安装 Node.js SDK:
npm install --save @cloudbase/node-sdk
functions/hello_world/index.js 内容改为:
const cloudbase = require("@cloudbase/node-sdk");
exports.main = async function () {
if (cloudbase) {
return "Happy Hack With Cloudbase!";
}
};
然后我们重新部署云函数:
cloudbase fn deploy hello_world -e <env-id>
在云函数的调用结果里,我们便可以看到结果:
app
.callFunction({
name: "hello_world"
})
.then((res) => {
console.log(res.result); // 'Happy Hack With Cloudbase!'
});