跳到主要内容

HTTP 云函数调用方式

CloudBase HTTP 云函数支持多种调用方式,满足不同场景和平台的需求。您可以根据实际情况选择最适合的调用方式。

调用方式概览​

调用方式适用场景特点
小程序调用微信小程序原生支持,支持流式传输,无需额外配置
HTTP API跨语言调用、第三方系统集成标准 REST API,支持所有编程语言
HTTP 访问服务浏览器环境、前端应用通过自定义域名调用,支持 CORS

通过小程序调用方法,无需配置或放通域名即可调用 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)

},
});

请求参数说明​

调用参数​

参数类型必填说明
namestring是云函数名称
configobject否配置对象
config.envstring否云开发环境 ID
dataobject否请求数据(body)
pathstring是请求路径
methodstring是请求方法,可选值:get / post / put / delete / head / options
headerobject否自定义请求头
enableChunkedboolean否是否启用流式传输
dataTypestring否指定响应的数据类型,仅非流式情况下生效
responseTypestring否指定响应的数据类型,仅非流式情况下生效
timeoutnumber否请求超时时间,单位为毫秒(ms),需设置小于 1500 ms
successfunction否请求成功的回调
failfunction否请求失败的回调
completefunction否请求结束的回调(成功或失败都会执行)
onHeadersReceivedfunction否流式模式下,收到响应头时的回调
onChunkedReceivedfunction否流式模式下,收到 chunk 数据时的回调

返回参数​

参数类型说明
datastring / Object / ArrayBuffer返回的数据内容,流式返回时为 ArrayBuffer
statusCodenumberHTTP 状态码
headerObject响应头

流式调用(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);
}
},
});

相关文档​