Access Cloud Functions via HTTP
HTTP cloud functions support configuring custom domains via the HTTP Access Service, enabling standard HTTP API invocation.
Prerequisites
Before you begin, make sure you have:
- Created an HTTP cloud function
- Configured the HTTP Access Service and custom domain
- Obtained the function's access URL
Configuring the HTTP Access Service
Step Instructions
- Create an HTTP cloud function: In the TCB console, create a new HTTP cloud function.
- Go to Function Details: After the function is created successfully, click the function name to go to the details page.
- Configure the access path: On the function configuration page, locate the "HTTP Access Service Path" option and click "Go to Settings".
- Set the domain and path: On the HTTP Access Service page, configure the custom domain and access path.
💡 Note: For detailed HTTP Access Service configuration methods, see the HTTP Access Service documentation.
HTTP Client Invocation Example
Below are complete examples of invoking HTTP cloud functions using different methods:
- cURL
- Fetch API
- XMLHttpRequest
- Axios
# GET Request Example
curl -X GET "https://your-domain.com/your-function-path" \
-H "Content-Type: application/json"
# POST Request Example
curl -X POST "https://your-domain.com/your-function-path" \
-H "Content-Type: application/json" \
-d '{
"name": "CloudBase",
"type": "serverless"
}'
# Authenticated Request
curl -X POST "https://your-domain.com/your-function-path" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-token" \
-d '{"data": "example"}'
// 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', // Includes cookies
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
console.log('Function returned 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;
}
}
// Usage example
callFunction();
postToFunction({ name: 'CloudBase', version: '2.0' });
// GET request
function callFunctionWithXHR() {
const xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', function () {
if (this.readyState === 4) {
if (this.status === 200) {
try {
const result = JSON.parse(this.responseText);
console.log('Request successful:', result);
} catch (error) {
console.error('Failed to parse response:', error);
}
} else {
console.error('Request failed:', this.status, this.statusText);
}
}
});
xhr.open('GET', 'https://your-domain.com/your-function-path');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.withCredentials = true; // Include credentials
xhr.send();
}
// POST request
function postWithXHR(data) {
const xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', function () {
if (this.readyState === 4) {
if (this.status === 200) {
const result = JSON.parse(this.responseText);
console.log('POST successful:', result);
} else {
console.error('POST failed:', this.status);
}
}
});
xhr.open('POST', 'https://your-domain.com/your-function-path');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.withCredentials = true;
xhr.send(JSON.stringify(data));
}
// Usage example
callFunctionWithXHR();
postWithXHR({ message: 'Hello CloudBase' });
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 the 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 fetched successfully:', result);
return result;
} catch (error) {
console.error('Failed to obtain 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;
}
}
// Usage example
getFunctionData();
postFunctionData({
user: 'developer',
action: 'create_project'
});
Request Parameters Description
URL Format
https://{custom-domain}/{service-path}
- Custom Domain: The domain name configured in the HTTP Access Service
- Service Path: The access path of the function, which can be set in the function configuration.
Common Request Headers
| Header | Description | Example Value |
|---|---|---|
Content-Type | Request content type | application/json |
Authorization | Authentication | Bearer your-token |
User-Agent | Client | MyApp/1.0 |
Error Handling
Common HTTP Status Codes
| Status Code | Description | Handling Suggestions |
|---|---|---|
200 | Request successful | Process the response data normally |
400 | Invalid request parameters | Check the request parameter format |
401 | Unauthorized | Check authentication credentials |
404 | Function not found | Check the URL path |
500 | Internal Server Error | Check the function code logic |
502 | Bad Gateway | Check whether the function is running properly |
504 | Gateway 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 the 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 invocation failed:', error);
// Handle differently based on error types
if (error.name === 'TypeError') {
return { success: false, error: 'Network connection failed' };
} else if (error.message.includes('404')) {
return { success: false, error: 'Function not found' };
} else {
return { success: false, error: error.message };
}
}
}
Performance Optimization Recommendations
1. Connection Reuse
// Use keep-alive connections
const agent = new https.Agent({
keepAlive: true,
maxSockets: 10,
});
fetch(url, {
agent: agent, // Node.js environment
});
2. Request Caching
// Simple in-memory cache implementation
const cache = new Map();
async function cachedFetch(url, options = {}, ttl = 60000) {
const cacheKey = `${url}_${JSON.stringify(options)}`;
const cached = cache.get(cacheKey);
if (cached && Date.now() - cached.timestamp < ttl) {
return cached.data;
}
const result = await fetch(url, options);
cache.set(cacheKey, {
data: result,
timestamp: Date.now(),
});
return result;
}
3. Concurrency Control
// Limit the number of concurrent requests
class RequestQueue {
constructor(maxConcurrent = 5) {
this.maxConcurrent = maxConcurrent;
this.running = 0;
this.queue = [];
}
async add(requestFn) {
return new Promise((resolve, reject) => {
this.queue.push({ requestFn, resolve, reject });
this.process();
});
}
async process() {
if (this.running >= this.maxConcurrent || this.queue.length === 0) {
return;
}
this.running++;
const { requestFn, resolve, reject } = this.queue.shift();
try {
const result = await requestFn();
resolve(result);
} catch (error) {
reject(error);
} finally {
this.running--;
this.process();
}
}
}
// Usage example
const requestQueue = new RequestQueue(3);
requestQueue.add(() => fetch('/api/function1'));
requestQueue.add(() => fetch('/api/function2'));
Security Considerations
1. HTTPS Usage
Security Reminder
Always use the HTTPS protocol in production environments to prevent data interception during transmission.
2. Authentication and Authorization
// Add authentication header
const token = localStorage.getItem('authToken');
fetch(url, {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
});
3. Input Validation
// Client-side parameter validation
function validateInput(data) {
if (!data || typeof data !== 'object') {
throw new Error('Invalid input data');
}
// Add specific validation logic
if (data.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) {
throw new Error('Invalid email format');
}
return true;
}