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 Method | Applicable Scenarios | Features |
|---|---|---|
| Mini Program Call | WeChat Mini Programs | Native support, streaming supported, no additional configuration needed |
| HTTP API | Cross-language calls, third-party system integration | Standard REST API, supports all programming languages |
| HTTP Access Service | Browser environment, frontend applications | Call via custom domain, supports CORS |
| SDK Call (Coming Soon) | Mini Programs, Web apps, mobile apps | Simple and easy to use, automatic authentication |
- Mini Program Call
- HTTP API Call
- HTTP Access Service Call
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).
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
| Parameter | Type | Required | Description |
|---|---|---|---|
name | string | Yes | Cloud function name |
config | object | No | Configuration object |
config.env | string | No | CloudBase environment ID |
data | object | No | Request data (body) |
path | string | Yes | Request path |
method | string | Yes | Request method, options: get / post / put / delete / head / options |
header | object | No | Custom request headers |
enableChunked | boolean | No | Whether to enable streaming |
dataType | string | No | Specify response data type, only effective in non-streaming mode |
responseType | string | No | Specify response data type, only effective in non-streaming mode |
timeout | number | No | Request timeout in milliseconds (ms), must be set to less than 1500 ms |
success | function | No | Callback on successful request |
fail | function | No | Callback on failed request |
complete | function | No | Callback when request ends (executed on both success and failure) |
onHeadersReceived | function | No | Callback when response headers are received in streaming mode |
onChunkedReceived | function | No | Callback when chunk data is received in streaming mode |
Response Parameters
| Parameter | Type | Description |
|---|---|---|
data | string / Object / ArrayBuffer | Returned data content, ArrayBuffer when streaming |
statusCode | number | HTTP status code |
header | Object | Response 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);
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);
}
},
});
Calling cloud functions through HTTP API supports cross-language access, suitable for server-side applications and third-party system integration.
HTTP API Call
Getting Access Token
Before calling, you need to obtain an access token (AccessToken). For how to obtain it, please refer to AccessToken Documentation.
API Call Format
Request URL:
POST https://{env-id}.api.tcloudbasegateway.com/v1/functions/{function-name}?webfn=true
When calling HTTP cloud functions, you must add the webfn=true parameter to the request URL, otherwise it will be called as a regular cloud function.
Request Headers:
Authorization: Bearer {access_token}
Content-Type: application/json
Call Examples
cURL
# Call regular cloud function
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
}'
# Call HTTP cloud function
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 Parameter Description
Path Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
env-id | string | Yes | CloudBase environment ID |
function-name | string | Yes | Cloud function name |
Query Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
webfn | string | No | Set to true when calling HTTP cloud functions |
Request Header Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
Authorization | string | Yes | Bearer Token authentication, format: Bearer {access_token} |
Content-Type | string | Yes | Request content type, usually application/json |
X-Qualifier | string | No | Specify the version of the function to call |
HTTP cloud functions support standard HTTP calls through custom domains, suitable for browser environments and frontend applications.
HTTP Access Service Call
Prerequisites
- Created an HTTP cloud function
- Configured HTTP access service and custom domain
- Obtained the function's access URL
Configure HTTP Access Service
- Create HTTP Cloud Function: Create a new HTTP cloud function in the CloudBase console
- Enter Function Details: After the function is created successfully, click the function name to enter the details page
- Configure Access Path: Find the "HTTP Access Service Path" option on the function configuration page and click "Go to Settings"
- Set Domain and Path: Configure custom domain and access path on the HTTP access service page
For detailed HTTP access service configuration methods, please refer to HTTP Access Service Documentation.
Client Call Examples
Fetch API
// GET request
async function callFunction() {
try {
const response = await fetch('https://your-domain.com/your-function-path', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include', // Include cookies
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
console.log('Function return result:', result);
return result;
} catch (error) {
console.error('Request failed:', error);
throw error;
}
}
// POST request
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 request failed:', error);
throw error;
}
}
Axios
import axios from 'axios';
// Configure axios instance
const api = axios.create({
baseURL: 'https://your-domain.com',
timeout: 10000,
headers: {
'Content-Type': 'application/json',
},
withCredentials: true,
});
// Request interceptor
api.interceptors.request.use(
(config) => {
// You can add authentication token here
// config.headers.Authorization = `Bearer ${getToken()}`;
return config;
},
(error) => {
return Promise.reject(error);
}
);
// Response interceptor
api.interceptors.response.use(
(response) => {
return response.data;
},
(error) => {
console.error('API request failed:', error.response?.data || error.message);
return Promise.reject(error);
}
);
// GET request
async function getFunctionData() {
try {
const result = await api.get('/your-function-path');
console.log('Data retrieved successfully:', result);
return result;
} catch (error) {
console.error('Failed to retrieve data:', error);
throw error;
}
}
// POST request
async function postFunctionData(data) {
try {
const result = await api.post('/your-function-path', data);
console.log('Data submitted successfully:', result);
return result;
} catch (error) {
console.error('Failed to submit data:', error);
throw error;
}
}
Error Handling
Common HTTP Status Codes
| Status Code | Description | Handling Suggestions |
|---|---|---|
200 | Request successful | Process response data normally |
400 | Request parameter error | Check request parameter format |
401 | Unauthorized | Check authentication information |
404 | Function does not exist | Check URL path |
500 | Internal server error | Check function code logic |
502 | Gateway error | Check if function is running properly |
504 | Request timeout | Optimize function execution time |
Error Handling Best Practices
async function callFunctionSafely(url, options = {}) {
try {
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
...options,
});
// Check response status
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('Function call failed:', error);
// Handle different error types
if (error.name === 'TypeError') {
return { success: false, error: 'Network connection failed' };
} else if (error.message.includes('404')) {
return { success: false, error: 'Function does not exist' };
} else {
return { success: false, error: error.message };
}
}
}
Related Documentation
HTTP API Authentication
Learn how to get and use access tokens
HTTP Access Service
Configure custom domains and access paths