HTTP 云函数调用方式
CloudBase HTTP 云函数支持多种调用方式,满足不同场景和平台的需求。您可以根据实际情况选择最适合的调用方式。
调用方式概览
| 调用方式 | 适用场景 | 特点 |
|---|---|---|
| 小程序调用 | 微信小程序 | 原生支持,支持流式传输,无需额外配置 |
| HTTP API | 跨语言调用、第三方系统集成 | 标准 REST API,支持所有编程语言 |
| HTTP 访问服务 | 浏览器环境、前端应用 | 通过自定义域名调用,支持 CORS |
| SDK 调用(敬请期待) | 小程序、Web 应用、移动应用 | 简单易用,自动处理认证 |
- 小程序调用
- HTTP API 调用
- HTTP 访问服务调用
通过小程序调用方法,无需配置或放通域名即可调用 HTTP 云函数,适合微信小程序开发。
小程序调用
通过微信小程序原生 SDK 中的 wx.cloud.callHTTPFunction 方法,可以直接调用 HTTP 云函数,支持流式传输(SSE)。
版本要求
调用 HTTP 云函数时,确保小程序基础库版本为 3.15.1 及以上。
调用方法
wx.cloud.callHTTPFunction 方法的调用方式与 wx.request 类似,支持多种请求方法和流式传输。
基础调用示例:
wx.cloud.callHTTPFunction({
name: 'my-http-function', // 云函数名称
config: {
env: 'your-env-id', // 可选:指定云开发环境 ID
},
data: { key: 'value' }, // 请求数据
path: '/api/hello', // 请求路径
method: 'post', // 请求方法
header: {
'X-Custom-Header': 'value', // 自定义请求头
},
timeout: 1500, // 超时时间(毫秒)
enableChunked: true, // 启用流式传输
onHeadersReceived: (res) => {
console.log("httpFunc headers received", res)
},
onChunkedReceived: (res) => {
console.log("chunked",res)
const arrayBuffer = res.data;
const uint8Array = new Uint8Array(arrayBuffer);
let str = '';
for (let i = 0; i < uint8Array.length; i++) {
str += String.fromCharCode(uint8Array[i]);
}
// 尝试解码 utf-8
try {
const decodedStr = decodeURIComponent(escape(str));
console.log('SSE chunk received:', decodedStr);
} catch (e) {
console.log('SSE chunk received (raw):', str);
}
},
success: (res) => {
console.log("httpFunc success", res)
},
fail: (err) => {
console.log("callHttpFunction err", err)
},
});
请求参数说明
调用参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
name | string | 是 | 云函数名称 |
config | object | 否 | 配置对象 |
config.env | string | 否 | 云开发环境 ID |
data | object | 否 | 请求数据(body) |
path | string | 是 | 请求路径 |
method | string | 是 | 请求方法,可选值:get / post / put / delete / head / options |
header | object | 否 | 自定义请求头 |
enableChunked | boolean | 否 | 是否启用流式传输 |
dataType | string | 否 | 指定响应的数据类型,仅非流式情况下生效 |
responseType | string | 否 | 指定响应的数据类型,仅非流式情况下生效 |
timeout | number | 否 | 请求超时时间,单位为毫秒(ms),需设置小于 1500 ms |
success | function | 否 | 请求成功的回调 |
fail | function | 否 | 请求失败的回调 |
complete | function | 否 | 请求结束的回调(成功或失败都会执行) |
onHeadersReceived | function | 否 | 流式模式下,收到响应头时的回调 |
onChunkedReceived | function | 否 | 流式模式下,收到 chunk 数据时的回调 |
返回参数
| 参数 | 类型 | 说明 |
|---|---|---|
data | string / Object / ArrayBuffer | 返回的数据内容,流式返回时为 ArrayBuffer |
statusCode | number | HTTP 状态码 |
header | Object | 响应头 |
流式调用(SSE)
wx.cloud.callHTTPFunction 支持流式调用,通过设置 enableChunked: true 开启流式传输,配合 onChunkedReceived 回调接收流式数据。适用于 AI 对话、实时数据推送等场景。
云函数侧示例(Express SSE)
const express = require('express');
const app = express();
app.get('/sse', (req, res) => {
// 1. 设置 SSE 必需的响应头
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
// 2. 发送一个初始注释(可选,用于避免某些代理超时)
res.write(': keep-alive\n\n');
// 3. 定时发送事件
const intervalId = setInterval(() => {
const data = { time: new Date().toISOString() };
// SSE 格式:data: <内容>\n\n
res.write(`data: ${JSON.stringify(data)}\n\n`);
}, 1000);
// 4. 客户端关闭连接时清理定时器
req.on('close', () => {
clearInterval(intervalId);
res.end();
});
});
app.listen(9000);
超时设置
函数配置时需注意超时时间设置。上述 demo 中的函数为持续发送消息,会在函数超时后自动中断。建议根据实际业务场景合理设置超时时间。
小程序侧示例
wx.cloud.callHTTPFunction({
name: 'express-sse', // 根据需要修改为实际函数名
path: '/sse',
method: 'GET',
enableChunked: true,
onHeadersReceived: (res) => {
console.log("httpFn headers received", res)
},
onChunkedReceived: (res) => {
console.log("chunked",res)
const arrayBuffer = res.data;
const uint8Array = new Uint8Array(arrayBuffer);
let str = '';
for (let i = 0; i < uint8Array.length; i++) {
str += String.fromCharCode(uint8Array[i]);
}
// 尝试解码 utf-8
try {
const decodedStr = decodeURIComponent(escape(str));
console.log('SSE chunk received:', decodedStr);
} catch (e) {
console.log('SSE chunk received (raw):', str);
}
},
});
通过 HTTP API 调用云函数支持跨语言访问,适合服务端应用和第三方系统集成。
HTTP API 调用
获取访问令牌
调用前需要先获取访问令牌(AccessToken),获取方式请参考 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 认证,格式为 Bearer {access_token} |
Content-Type | string | 是 | 请求内容类型,通常为 application/json |
X-Qualifier | string | 否 | 指定调用函数的版本 |
HTTP 云函数支持通过自定义域名进行标准的 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 访问服务
配置自定义域名和访问路径