Chainlink Functions编码错误排查:无法获取指定API数据
问题诊断
你遇到的Error: input into Functions.encodeString is invalid错误,核心原因有两个:
- API响应结构解析错误:Sportmonks的
/fixtures/date端点返回的data字段是赛事对象数组,而非单个对象。当前代码中apiResponse.data.id会返回undefined,因为数组本身没有id属性。 - 类型不匹配:即便正确获取到赛事ID,它也是数字类型,而
Functions.encodeString要求输入必须是字符串类型,直接传入数字会触发类型错误。
解决方案
针对以上问题,修改Chainlink Functions的JavaScript执行代码,调整响应解析逻辑并处理类型转换:
- 正确遍历API返回的赛事数组,获取目标字段(比如第一个赛事的ID)。
- 将数字类型的字段转换为字符串后,再传入
Functions.encodeString。 - 增加空数组判断,避免因API返回无数据导致的错误。
修改后的代码示例
将合约中的source变量替换为以下代码:
const apiResponse = await Functions.makeHttpRequest({ url: 'YOUR_FULL_API_URL_WITH_API_TOKEN' // 确保URL包含正确的api_token参数,且参数用?开头 }); if (apiResponse.error) { console.log('API请求错误:', apiResponse.error); throw new Error('API请求失败'); } // 检查data是否为非空数组 if (!Array.isArray(apiResponse.data) || apiResponse.data.length === 0) { throw new Error('未获取到赛事数据'); } // 获取第一个赛事的ID,并转换为字符串 let dataPoint1 = apiResponse.data[0].id.toString(); console.log('获取到的赛事ID:', dataPoint1); return Functions.encodeString(dataPoint1);
同时,确保你的API URL格式正确:参数需用?开头,示例格式如下:https://api.sportmonks.com/v3/football/fixtures/date/2024-05-15?includes=scores&api_token=YOUR_API_KEY
调试技巧
- 在Chainlink Functions执行历史中查看Computation环节的日志:通过
console.log(apiResponse.data)打印完整API响应结构,确认目标字段的路径是否正确。 - 先尝试返回固定字符串(比如
return Functions.encodeString("test")),验证合约端的回调逻辑是否正常,排除API解析之外的问题。
内容的提问来源于stack exchange,提问作者Kojrey
相关产品推荐
相关产品推荐

