通过 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 |