快速开始
#
第 1 步:创建目录和云函数文件- 在本地创建一个空的文件夹,作为项目的根目录。
- 进入项目根目录,创建 functions 文件夹。
- 在 functions 下创建 hello_world 文件夹,包含 index.js 与 package.json 两个文件。
此时目录结构如下:
└── functions └── hello_world ├── index.js └── package.json
index.js 内容如下:
exports.main = async function () { return "Hello World!";};
package.json 内容如下:
{ "name": "hello_world", "version": "1.0.0", "main": "index.js"}
#
第 2 步:发布云函数- 命令行工具
- 小程序开发者工具
- 安装并登录 CLI 工具;
- 在项目根目录运行以下命令,并且使用默认配置:
cloudbase fn deploy hello_world -e <env-id>
#
第 3 步:调用云函数调用云函数有两种方法:
- 使用云开发 SDK;
- 使用 HTTP 访问服务。
#
使用 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!' });