将GoClimate API的Curl认证请求转换为JavaScript Fetch API调用
将GoClimate航班碳足迹API的Curl请求转为JavaScript Fetch调用
转换后的Fetch代码
// 替换为你的实际API密钥 const API_KEY = 'YOUR_API_KEY'; // 构建查询参数 const params = new URLSearchParams(); // 添加往返航班段参数 params.append('segments[0][origin]', 'ARN'); params.append('segments[0][destination]', 'BCN'); params.append('segments[1][origin]', 'BCN'); params.append('segments[1][destination]', 'ARN'); // 添加舱位等级参数 params.append('cabin_class', 'economy'); // 添加目标货币参数(多次append处理数组格式) params.append('currencies[]', 'SEK'); params.append('currencies[]', 'USD'); // 发送API请求 fetch(`https://api.goclimate.com/v1/flight_footprint?${params}`, { method: 'GET', headers: { // 对应Curl的-u认证:API密钥作为用户名,密码留空,转Base64编码 'Authorization': `Basic ${btoa(`${API_KEY}:`)}` } }) .then(response => { if (!response.ok) { throw new Error(`请求失败: ${response.status}`); } return response.json(); }) .then(data => { console.log('碳足迹查询结果:', data); }) .catch(error => { console.error('请求出错:', error); });
关键转换说明
- 认证处理:原Curl的
-u YOUR_API_KEY:对应HTTP Basic认证,通过btoa()将API_KEY:编码为Base64字符串,放入Authorization请求头。 - 请求方法与参数:Curl的
-G参数表示将-d参数转为URL查询字符串,因此Fetch使用GET方法,通过URLSearchParams构建参数并拼接到URL后。 - 数组参数处理:对于
currencies[]这类数组格式的参数,通过多次调用append()添加多个值,匹配API的参数格式要求。
内容的提问来源于stack exchange,提问作者BouldersDev
相关产品推荐
相关产品推荐

