Skip to main content

HTTP Cloud Function Call Methods

CloudBase HTTP cloud functions support multiple call methods to meet the needs of different scenarios and platforms. You can choose the most suitable call method based on your actual situation.

Call Methods Overview

Call MethodApplicable ScenariosFeatures
Mini Program CallWeChat Mini ProgramsNative support, streaming supported, no additional configuration needed
HTTP APICross-language calls, third-party system integrationStandard REST API, supports all programming languages
HTTP Access ServiceBrowser environment, frontend applicationsCall via custom domain, supports CORS
SDK Call (Coming Soon)Mini Programs, Web apps, mobile appsSimple and easy to use, automatic authentication

Call HTTP cloud functions through Mini Program methods without configuring or whitelisting domains, suitable for WeChat Mini Program development.

Mini Program Call

Through the wx.cloud.callHTTPFunction method in the WeChat Mini Program native SDK, you can directly call HTTP cloud functions with support for streaming (SSE).

Version Requirement

When calling HTTP cloud functions, ensure the Mini Program base library version is 3.15.1 or above.

Call Method

The wx.cloud.callHTTPFunction method works similarly to wx.request, supporting multiple request methods and streaming.

Basic call example:

wx.cloud.callHTTPFunction({
name: 'my-http-function', // Cloud function name
config: {
env: 'your-env-id', // Optional: specify CloudBase environment ID
},
data: { key: 'value' }, // Request data
path: '/api/hello', // Request path
method: 'post', // Request method
header: {
'X-Custom-Header': 'value', // Custom request header
},
timeout: 1500, // Timeout in milliseconds
enableChunked: true, // Enable streaming
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]);
}
// Try to decode 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)

},
});

Request Parameter Description

Call Parameters

ParameterTypeRequiredDescription
namestringYesCloud function name
configobjectNoConfiguration object
config.envstringNoCloudBase environment ID
dataobjectNoRequest data (body)
pathstringYesRequest path
methodstringYesRequest method, options: get / post / put / delete / head / options
headerobjectNoCustom request headers
enableChunkedbooleanNoWhether to enable streaming
dataTypestringNoSpecify response data type, only effective in non-streaming mode
responseTypestringNoSpecify response data type, only effective in non-streaming mode
timeoutnumberNoRequest timeout in milliseconds (ms), must be set to less than 1500 ms
successfunctionNoCallback on successful request
failfunctionNoCallback on failed request
completefunctionNoCallback when request ends (executed on both success and failure)
onHeadersReceivedfunctionNoCallback when response headers are received in streaming mode
onChunkedReceivedfunctionNoCallback when chunk data is received in streaming mode

Response Parameters

ParameterTypeDescription
datastring / Object / ArrayBufferReturned data content, ArrayBuffer when streaming
statusCodenumberHTTP status code
headerObjectResponse headers

Streaming Call (SSE)

wx.cloud.callHTTPFunction supports streaming calls. Enable streaming by setting enableChunked: true and use the onChunkedReceived callback to receive streaming data. Suitable for AI conversations, real-time data push, and similar scenarios.

Cloud Function Side Example (Express SSE)

const express = require('express');
const app = express();

app.get('/sse', (req, res) => {
// 1. Set required SSE response headers
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});

// 2. Send an initial comment (optional, to avoid some proxy timeouts)
res.write(': keep-alive\n\n');

// 3. Send events at intervals
const intervalId = setInterval(() => {
const data = { time: new Date().toISOString() };
// SSE format: data: <content>\n\n
res.write(`data: ${JSON.stringify(data)}\n\n`);
}, 1000);

// 4. Clean up timer when client closes connection
req.on('close', () => {
clearInterval(intervalId);
res.end();
});
});

app.listen(9000);
Timeout Settings

Pay attention to the timeout configuration when setting up the function. The demo above sends messages continuously and will be automatically interrupted when the function times out. It is recommended to set the timeout appropriately based on your actual business scenario.

Mini Program Side Example

wx.cloud.callHTTPFunction({
name: 'express-sse', // Modify to your actual function name as needed
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]);
}
// Try to decode utf-8
try {
const decodedStr = decodeURIComponent(escape(str));
console.log('SSE chunk received:', decodedStr);
} catch (e) {
console.log('SSE chunk received (raw):', str);
}
},
});