You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 17:53:15