跳到主要内容

通过 HTTP 访问云函数

HTTP 云函数支持通过 HTTP 访问服务 配置自定义域名,实现标准的 HTTP API 调用。

前提条件

在开始之前,请确保您已经:

  • 创建了 HTTP 云函数
  • 配置了 HTTP 访问服务和自定义域名
  • 获取了函数的访问 URL

配置 HTTP 访问服务

步骤说明

  1. 创建 HTTP 云函数:在云开发控制台创建一个新的 HTTP 云函数
  2. 进入函数详情:函数创建成功后,点击函数名称进入详情页面
  3. 配置访问路径:在函数配置页面找到「HTTP 访问服务路径」选项,点击「去设定」
  4. 设置域名和路径:在 HTTP 访问服务页面配置自定义域名和访问路径

💡 提示:详细的 HTTP 访问服务配置方法,请参考 HTTP 访问服务文档

HTTP 客户端调用示例

以下展示了使用不同方式调用 HTTP 云函数的完整示例:

# 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"}'

请求参数说明

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;
}

相关文档