云函数调用方式
CloudBase 云函数支持多种调用方式,满足不同场景和平台的需求。您可以根据实际情况选择最适合的调用方式。
调用方式概览
| 调用方式 | 适用场景 | 特点 |
|---|---|---|
| SDK 调用 | 小程序、Web 应用、移动应用 | 简单易用,自动处理认证 |
| HTTP API | 跨语言调用、第三方系统集成 | 标准 REST API,支持所有语言 |
| Web 客户端 | 浏览器环境、前端应用 | 支持 CORS,直接 HTTP 访问 |
| 小程序调用 | 微信小程序 | 原生支持,无需额外配置 |
- SDK 调用
- HTTP API 调用
- Web 客户端调用
- 小程序调用
SDK 调用
通过 CloudBase SDK 调用云函数是最简单的方式,SDK 会自动处理认证和请求封装。
Web SDK 调用
import tcb from '@cloudbase/js-sdk';
// 初始化
const app = tcb.init({
env: 'your-env-id'
});
// 调用云函数
async function callFunction() {
try {
const result = await app.callFunction({
name: 'hello-world',
data: {
name: 'CloudBase',
message: 'Hello from Web'
}
});
console.log('调用成功:', result);
return result.result;
} catch (error) {
console.error('调用失败:', error);
throw error;
}
}
// 使用示例
callFunction().then(result => {
console.log('函数返回:', result);
});
Node.js SDK 调用
const tcb = require('@cloudbase/node-sdk');
// 初始化
const app = tcb.init({
env: 'your-env-id',
secretId: 'your-secret-id',
secretKey: 'your-secret-key'
});
// 调用云函数
async function callFunction() {
try {
const result = await app.callFunction({
name: 'hello-world',
data: {
name: 'CloudBase',
message: 'Hello from Node.js'
}
});
return result.result;
} catch (error) {
console.error('调用失败:', error);
throw error;
}
}
小程序 SDK 调用
// 小程序中调用云函数
wx.cloud.callFunction({
name: 'hello-world',
data: {
name: 'CloudBase',
message: 'Hello from MiniProgram'
},
success: res => {
console.log('调用成功:', res.result);
},
fail: err => {
console.error('调用失败:', err);
}
});
// 使用 Promise 方式
async function callFunction() {
try {
const result = await wx.cloud.callFunction({
name: 'hello-world',
data: { message: 'Hello' }
});
return result.result;
} catch (error) {
console.error('调用失败:', error);
throw error;
}
}
SDK 调用优势
- 自动认证 - SDK 自动处理用户认证和权限验证
- 错误处理 - 统一的错误处理和重试机制
- 类型安全 - TypeScript 支持,提供完整的类型定义
- 简单易用 - 封装了底层 HTTP 请求细节
HTTP API 调用
通过 HTTP API 调用云函数支持跨语言访问,适合第三方系统集成。
获取访问令牌
访问令牌的获取方式请参考 AccessToken 文档。
API 调用格式
请求 URL:
POST https://{env-id}.api.tcloudbasegateway.com/v1/functions/{function-name}
请求头:
Authorization: Bearer {access_token}
Content-Type: application/json
多语言调用示例
cURL
# 基础调用
curl -L 'https://your-env-id.api.tcloudbasegateway.com/v1/functions/your-function-name' \
-H 'Accept: application/json' \
-H 'Authorization: Bearer your-access-token' \
-H 'Content-Type: application/json' \
-d '{
"message": "Hello CloudBase",
"timestamp": 1640995200000
}'
# HTTP 云函数
curl -L 'https://your-env-id.api.tcloudbasegateway.com/v1/functions/your-web-function?webfn=true' \
-H 'Accept: application/json' \
-H 'Authorization: Bearer your-access-token' \
-H 'Content-Type: application/json' \
-d '{
"path": "/api/users",
"method": "GET"
}'
JavaScript
async function callCloudFunction(functionName, data, token) {
try {
const response = await fetch(
`https://your-env-id.api.tcloudbasegateway.com/v1/functions/${functionName}`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(data)
}
);
if (!response.ok) {
const errorData = await response.json();
throw new Error(`HTTP ${response.status}: ${errorData.message}`);
}
const result = await response.json();
return result;
} catch (error) {
console.error('云函数调用失败:', error);
throw error;
}
}
// 使用示例
const token = 'your-access-token';
callCloudFunction('hello-world', { name: 'CloudBase' }, token)
.then(result => {
console.log('调用成功:', result);
})
.catch(error => {
console.error('调用失败:', error);
});
Python
import requests
import json
def call_cloud_function(env_id, function_name, data, access_token):
"""调用云函数"""
url = f"https://{env_id}.api.tcloudbasegateway.com/v1/functions/{function_name}"
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json',
'Accept': 'application/json'
}
try:
response = requests.post(url, headers=headers, json=data, timeout=30)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")
raise
# 使用示例
env_id = "your-env-id"
function_name = "hello-world"
data = {"message": "Hello from Python"}
token = "your-access-token"
try:
result = call_cloud_function(env_id, function_name, data, token)
print("调用成功:", result)
except Exception as e:
print("调用失败:", e)
API 参数说明
路径参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
env-id | string | 是 | 环境 ID |
function-name | string | 是 | 函数名称 |
查询参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
webfn | string | 否 | 调用 HTTP 云函数时设置为 true |
请求头参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
Authorization | string | 是 | Bearer Token 认证 |
Content-Type | string | 是 | 请求内容类型,通常为 application/json |
X-Qualifier | string | 否 | 指定调用函数的版本 |
Web 客户端调用
HTTP 云函数支持通过自定义域名进行标准的 HTTP 调用,适合浏览器环境和前端应用。
前提条件
- 创建了 HTTP 云函数
- 配置了 HTTP 访问服务和自定义域名
- 获取了函数的访问 URL
配置 HTTP 访问服务
- 创建 HTTP 云函数:在云开发控制台创建一个新的 HTTP 云函数
- 进入函数详情:函数创建成功后,点击函数名称进入详情页面
- 配置访问路径:在函数配置页面找到「HTTP 访问服务路径」选项,点击「去设定」
- 设置域名和路径:在 HTTP 访问服务页面配置自定义域名和访问路径
💡 提示:详细的 HTTP 访问服务配置方法,请参考 HTTP 访问服务文档。
客户端调用示例
Fetch API
// GET 请求
async function callFunction() {
try {
const response = await fetch('https://your-domain.com/your-function-path', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include', // 包含 cookies
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
console.log('函数返回结果:', result);
return result;
} catch (error) {
console.error('请求失败:', error);
throw error;
}
}
// POST 请求
async function postToFunction(data) {
try {
const response = await fetch('https://your-domain.com/your-function-path', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
credentials: 'include',
});
const result = await response.json();
return result;
} catch (error) {
console.error('POST 请求失败:', error);
throw error;
}
}
Axios
import axios from 'axios';
// 配置 axios 实例
const api = axios.create({
baseURL: 'https://your-domain.com',
timeout: 10000,
headers: {
'Content-Type': 'application/json',
},
withCredentials: true,
});
// 请求拦截器
api.interceptors.request.use(
(config) => {
// 可以在这里添加认证 token
// config.headers.Authorization = `Bearer ${getToken()}`;
return config;
},
(error) => {
return Promise.reject(error);
}
);
// 响应拦截器
api.interceptors.response.use(
(response) => {
return response.data;
},
(error) => {
console.error('API 请求失败:', error.response?.data || error.message);
return Promise.reject(error);
}
);
// GET 请求
async function getFunctionData() {
try {
const result = await api.get('/your-function-path');
console.log('获取数据成功:', result);
return result;
} catch (error) {
console.error('获取数据失败:', error);
throw error;
}
}
// POST 请求
async function postFunctionData(data) {
try {
const result = await api.post('/your-function-path', data);
console.log('提交数据成功:', result);
return result;
} catch (error) {
console.error('提交数据失败:', error);
throw error;
}
}
错误处理
常见 HTTP 状态码
| 状态码 | 说明 | 处理建议 |
|---|---|---|
200 | 请求成功 | 正常处理响应数据 |
400 | 请求参数错误 | 检查请求参数格式 |
401 | 未授权 | 检查认证信息 |
404 | 函数不存在 | 检查 URL 路径 |
500 | 服务器内部错误 | 检查函数代码逻辑 |
502 | 网关错误 | 检查函数是否正常运行 |
504 | 请求超时 | 优化函数执行时间 |
错误处理最佳实践
async function callFunctionSafely(url, options = {}) {
try {
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
...options,
});
// 检查响应状态
if (!response.ok) {
const errorData = await response.text();
throw new Error(`HTTP ${response.status}: ${errorData}`);
}
const result = await response.json();
return { success: true, data: result };
} catch (error) {
console.error('函数调用失败:', error);
// 根据错误类型进行不同处理
if (error.name === 'TypeError') {
return { success: false, error: '网络连接失败' };
} else if (error.message.includes('404')) {
return { success: false, error: '函数不存在' };
} else {
return { success: false, error: error.message };
}
}
}
小程序调用
微信小程序可以直接使用 wx.cloud.callFunction API 调用云函数,无需额外配置。
基础调用
// 基础调用方式
wx.cloud.callFunction({
name: 'hello-world',
data: {
name: 'CloudBase',
message: 'Hello from MiniProgram'
},
success: res => {
console.log('调用成功:', res.result);
},
fail: err => {
console.error('调用失败:', err);
}
});
Promise 方式调用
// 使用 Promise 方式
async function callFunction() {
try {
const result = await wx.cloud.callFunction({
name: 'hello-world',
data: {
message: 'Hello from Promise'
}
});
console.log('调用成功:', result.result);
return result.result;
} catch (error) {
console.error('调用失败:', error);
throw error;
}
}
// 使用示例
callFunction().then(result => {
console.log('函数返回:', result);
});
在页面中使用
// pages/index/index.js
Page({
data: {
result: null,
loading: false
},
// 调用云函数
async callCloudFunction() {
this.setData({ loading: true });
try {
const result = await wx.cloud.callFunction({
name: 'getUserInfo',
data: {
userId: wx.getStorageSync('userId')
}
});
this.setData({
result: result.result,
loading: false
});
wx.showToast({
title: '获取成功',
icon: 'success'
});
} catch (error) {
console.error('调用失败:', error);
this.setData({ loading: false });
wx.showToast({
title: '获取失败',
icon: 'error'
});
}
},
onLoad() {
// 页面加载时调用
this.callCloudFunction();
}
});
错误处理
// 完整的错误处理示例
async function callFunctionWithErrorHandling(functionName, data) {
try {
const result = await wx.cloud.callFunction({
name: functionName,
data: data
});
// 检查业务逻辑错误
if (result.result.code !== 0) {
throw new Error(result.result.message || '业务处理失败');
}
return result.result.data;
} catch (error) {
console.error('云函数调用失败:', error);
// 根据错误类型显示不同提示
let errorMessage = '操作失败';
if (error.errCode === -1) {
errorMessage = '网络连接失败,请检查网络';
} else if (error.errCode === -404001) {
errorMessage = '云函数不存在';
} else if (error.message) {
errorMessage = error.message;
}
wx.showToast({
title: errorMessage,
icon: 'error'
});
throw error;
}
}
批量调用
// 批量调用多个云函数
async function batchCallFunctions() {
const functions = [
{ name: 'getUserInfo', data: { userId: 'user1' } },
{ name: 'getOrderList', data: { status: 'pending' } },
{ name: 'getNotifications', data: { unread: true } }
];
try {
const results = await Promise.all(
functions.map(func =>
wx.cloud.callFunction({
name: func.name,
data: func.data
})
)
);
const [userInfo, orderList, notifications] = results.map(r => r.result);
return {
userInfo,
orderList,
notifications
};
} catch (error) {
console.error('批量调用失败:', error);
throw error;
}
}
小程序调用优势
- 原生支持 - 微信小程序原生支持云函数调用
- 自动认证 - 自动携带用户身份信息
- 简单易用 - API 简洁,易于使用
- 性能优化 - 针对小程序环境优化的网络请求
选择调用方式
根据场景选择
- 小程序开发 → 使用小程序 SDK 调用
- Web 应用开发 → 使用 Web SDK 调用
- 服务端开发 → 使用 Node.js SDK 调用
- 第三方系统集成 → 使用 HTTP API 调用
- 前端直接访问 → 使用 Web 客户端调用
性能对比
| 调用方式 | 性能 | 易用性 | 功能完整性 |
|---|---|---|---|
| SDK 调用 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| HTTP API | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ |
| Web 客户端 | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ |
| 小程序调用 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
相关文档
📄️ HTTP API 认证
了解如何获取和使用访问令牌
📄️ HTTP 访问服务
配置自定义域名和访问路径