通过 HTTP 访问云函数
HTTP 云函数支持通过 HTTP 访问服务 配置自定义域名,实现标准的 HTTP API 调用。
前提条件
在开始之前,请确保您已经:
- 创建了 HTTP 云函数
- 配置了 HTTP 访问服务和自定义域名
- 获取了函数的访问 URL
配置 HTTP 访问服务
步骤说明
- 创建 HTTP 云函数:在云开发控制台创建一个新的 HTTP 云函数
- 进入函数详情:函数创建成功后,点击函数名称进入详情页面
- 配置访问路径:在函数配置页面找到「HTTP 访问服务路径」选项,点击「去设定」
- 设置域名和路径:在 HTTP 访问服务页面配置自定义域名和访问路径
💡 提示:详细的 HTTP 访问服务配置方法,请参考 HTTP 访问服务文档。
HTTP 客户端调用示例
以下展示了使用不同方式调用 HTTP 云函数的完整示例:
- cURL
- Fetch API
- XMLHttpRequest
- Axios
# GET 请求示例
curl -X GET "https://your-domain.com/your-function-path" \
-H "Content-Type: application/json"
# POST 请求示例
curl -X POST "https://your-domain.com/your-function-path" \
-H "Content-Type: application/json" \
-d '{
"name": "CloudBase",
"type": "serverless"
}'
# 带认证头的请求
curl -X POST "https://your-domain.com/your-function-path" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-token" \
-d '{"data": "example"}'
// 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;
}
}
// 使用示例
callFunction();
postToFunction({ name: 'CloudBase', version: '2.0' });
// GET 请求
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('请求成功:', result);
} catch (error) {
console.error('解析响应失败:', error);
}
} else {
console.error('请求失败:', this.status, this.statusText);
}
}
});
xhr.open('GET', 'https://your-domain.com/your-function-path');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.withCredentials = true; // 包含认证信息
xhr.send();
}
// POST 请求
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 成功:', result);
} else {
console.error('POST 失败:', 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));
}
// 使用示例
callFunctionWithXHR();
postWithXHR({ message: 'Hello CloudBase' });
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;
}
}
// 使用示例
getFunctionData();
postFunctionData({
user: 'developer',
action: 'create_project'
});
请求参数说明
URL 格式
https://{自定义域名}/{服务路径}
- 自定义域名:在 HTTP 访问服务中配置的域名
- 服务路径:函数的访问路径,可在函数配置中设置
常用请求头
| 请求头 | 说明 | 示例值 |
|---|---|---|
Content-Type | 请求内容类型 | application/json |
Authorization | 认证信息 | Bearer your-token |
User-Agent | 客户端标识 | MyApp/1.0 |
错误处理
常见 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 };
}
}
}
性能优化建议
1. 连接复用
// 使用 keep-alive 连接
const agent = new https.Agent({
keepAlive: true,
maxSockets: 10,
});
fetch(url, {
agent: agent, // Node.js 环境
});
2. 请求缓存
// 简单的内存缓存实现
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. 并发控制
// 限制并发请求数量
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();
}
}
}
// 使用示例
const requestQueue = new RequestQueue(3);
requestQueue.add(() => fetch('/api/function1'));
requestQueue.add(() => fetch('/api/function2'));
安全注意事项
1. HTTPS 使用
安全提醒
生产环境中务必使用 HTTPS 协议,避免数据传输过程中被窃取。
2. 认证和授权
// 添加认证头
const token = localStorage.getItem('authToken');
fetch(url, {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
});
3. 输入验证
// 客户端参数验证
function validateInput(data) {
if (!data || typeof data !== 'object') {
throw new Error('无效的输入数据');
}
// 添加具体的验证逻辑
if (data.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) {
throw new Error('邮箱格式不正确');
}
return true;
}