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

调用apilayer API时API密钥未找到错误及正确配置方法

问题排查与修复:apilayer API密钥未被正确携带

核心错误原因

你创建了包含API密钥的requestOptions配置对象,但**fetchRates函数调用fetch时完全没用到这个配置**,导致请求根本没带上API密钥,所以返回"no API key found in the request"错误。

修复步骤

1. 修改fetchRates函数,传入请求配置

把requestOptions作为第二个参数传给fetch,确保请求携带API密钥:

async function fetchRates(base = "USD") {
    const res = await fetch(`${endpoint}?base=${base}`, requestOptions); // 添加requestOptions参数
    const rates = await res.json();
    return rates;
}

2. 修复其他潜在问题

  • 代码中ratesByBase变量未声明,需要在全局作用域或函数外层定义:
// 全局声明存储汇率的对象
const ratesByBase = {};
  • convert函数目前仅实现了获取汇率的逻辑,可补充转换计算逻辑:
async function convert(amount, from, to){
    if (!ratesByBase[from]) {
        console.log(`Oh no! we don't have ${from} to convert to ${to}, so let's go get it`);
        const rates = await fetchRates(from);
        ratesByBase[from] = rates;
    }
    // 补充货币转换计算
    const rate = ratesByBase[from].quotes[`${from}${to}`];
    return amount * rate;
}

验证修复

修改后重新运行代码,执行convert(100, 'CAD', 'USD'),此时请求会正确携带API密钥,应该能正常获取汇率并完成转换。

内容的提问来源于stack exchange,提问作者Muhammad Ahmad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 18:45:38