云函数调用方式
CloudBase 云函数支持多种调用方式,满足不同场景和平台的需求。您可以根据实际情况选择最适合的调用方式。
调用方式概览
| 调用方式 | 适用场景 | 特点 |
|---|---|---|
| HTTP API | 跨语言调用、第三方系统集成 | 标准 REST API,支持所有语言 |
| Web 客户端 | 浏览器环境、前端应用 | 支持 CORS,直接 HTTP 访问 |
| SDK 调用(敬请期待) | 小程序、Web 应用、移动应用 | 简单易用,自动处理认证 |
| 小程序调用(敬请期待) | 微信小程序 | 原生支持,无需额外配置 |
- HTTP API 调用
- HTTP访问服务调用
通过 HTTP API 调用云函数支持跨语言访问,适合第三方系统集成。
获取访问令牌
访问令牌的获取方式请参考 AccessToken 文档。
API 调用格式
请求 URL:
POST https://{env-id}.api.tcloudbasegateway.com/v1/functions/{function-name}?webfn=true
⚠️ 注意:调用 HTTP 云函数时,必须在请求 URL 中添加
webfn=true参数。
请求头:
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"
}'
API 参数说明
路径参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
env-id | string | 是 | 环境 ID |
function-name | string | 是 | 函数名称 |
查询参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
webfn | string | 否 | 调用 HTTP 云函数时设置为 true |
请求头参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
Authorization | string | 是 | Bearer Token 认证 |
Content-Type | string | 是 | 请求内容类型,通常为 application/json |
X-Qualifier | string | 否 | 指定调用函数的版本 |
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 };
}
}
}
相关文档
📄️ HTTP API 认证
了解如何获取和使用访问令牌
📄️ HTTP 访问服务
配置自定义域名和访问路径