跳到主要内容

Functions Framework 快速开始

本文介绍使用 @cloudbase/functions-framework 框架进行开发,它提供了更简洁的函数式编程体验。

前置条件

在开始之前,请确保您已经:

  • 安装了 Node.js (推荐 v18 或更高版本)
  • 拥有腾讯云账号并开通了 CloudBase 服务
  • 了解基本的 Node.js 开发知识

第一步:创建项目目录

创建名为 my-web-function 的新目录,并进入该目录:

mkdir my-web-function
cd my-web-function

第二步:初始化项目配置

package.json 文件:

{
"name": "my-web-function",
"version": "1.0.0",
"main": "index.js",
"dependencies": {
"@cloudbase/functions-framework": "^1.14.0"
}
}

第三步:编写示例代码

index.js 文件:

exports.main = async function(event, context) {
const { httpContext } = context;
const { url, httpMethod } = httpContext;
const path = new URL(url).pathname
// 处理不同的 HTTP 方法
switch (httpMethod) {
case 'GET':
return {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
message: 'Hello from Web Function',
path,
timestamp: new Date().toISOString()
})
};

case 'POST':
return {
statusCode: 201,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
message: 'Data received',
data: JSON.parse(body || '{}')
})
};

default:
return {
statusCode: 405,
body: JSON.stringify({ error: 'Method not allowed' })
};
}
};

第四步: 编写启动脚本

创建 scf_bootstrap 文件:

#!/bin/bash
node node_modules/@cloudbase/functions-framework/bin/tcb-ff.js --port=9000 --logDirname=/tmp/logs --interceptOutput=false --extendedContextKey=X-Cloudbase-Context
注意

scf_bootstrap 文件需要具有可执行权限,在 Linux/macOS 系统中使用 chmod +x scf_bootstrap 命令设置权限。

第五步:部署到 CloudBase HTTP 云函数

准备部署文件

确保您的项目目录包含以下文件:

my-web-function/
|-- scf_bootstrap
├── package.json
└── index.js

通过控制台部署

  1. 登录 CloudBase 控制台
  2. 选择您的环境,进入「云函数」页面
  3. 点击「新建云函数」
  4. 选择「HTTP 云函数」
  5. 填写函数名称(如:helloworld
  6. 选择运行时:Node.js 18.x
  7. 选择「本地上传」方式
  8. 将项目文件打包为 zip 文件并上传
  9. 点击「确定」完成部署

通过 CLI 部署(敬请期待)

打包项目

如果需要手动打包,可以使用以下命令:

# 创建 zip 包
zip -r helloworld.zip package.json index.js

第七步:访问您的应用

部署成功后,您可以参考Web 客户端调用设置自定义域名访问HTTP 云函数

下一步