使用fastforex.io API获取汇率时表格数据显示undefined求助
问题:表格中汇率数据显示undefined
我尝试用fastforex.io API获取汇率数据,但表格里的汇率始终显示undefined,代码如下:
<!DOCTYPE html> <html> <head> <title>Currency Conversion</title> </head> <body> <h1>Currency Conversion</h1> <table> <tr> <th>Currency</th> <th>Exchange Rate</th> </tr> <tr> <td>EUR</td> <td id="eur"></td> </tr> <tr> <td>GBP</td> <td id="gbp"></td> </tr> <tr> <td>CHF</td> <td id="chf"></td> </tr> </table> <script> // Fetch the exchange rates from the API fetch(`https://api.fastforex.io/fetch-multi?api_key=1234567891221&from=USD&to=EUR,GBP,CHF `) .then(response => response.json()) .then(data => { // Update the exchange rates in the table document.getElementById("eur").innerHTML = data.EUR; document.getElementById("gbp").innerHTML = data.GBP; document.getElementById("chf").innerHTML = data.CHF; }); </script> </body> </html>
问题原因及解决方法
- API返回结构错误:fastforex的
fetch-multi接口返回的汇率数据嵌套在results字段下,不是直接挂在顶级对象上,直接取data.EUR自然会得到undefined。 - URL末尾的换行符:fetch URL末尾有多余换行,可能导致请求异常,需删除。
- 无效API密钥:代码里的
api_key=1234567891221是示例密钥,必须替换成你在fastforex.io获取的有效密钥。 - 缺少错误处理:未处理请求失败或返回错误的情况,无法排查问题。
修改后的代码
<!DOCTYPE html> <html> <head> <title>Currency Conversion</title> </head> <body> <h1>Currency Conversion</h1> <table> <tr> <th>Currency</th> <th>Exchange Rate</th> </tr> <tr> <td>EUR</td> <td id="eur"></td> </tr> <tr> <td>GBP</td> <td id="gbp"></td> </tr> <tr> <td>CHF</td> <td id="chf"></td> </tr> </table> <script> // 替换为你自己的有效API密钥 const API_KEY = "your-real-api-key"; fetch(`https://api.fastforex.io/fetch-multi?api_key=${API_KEY}&from=USD&to=EUR,GBP,CHF`) .then(response => { if (!response.ok) { throw new Error(`请求失败:${response.status}`); } return response.json(); }) .then(data => { // 从results字段中获取汇率数据 document.getElementById("eur").textContent = data.results.EUR; document.getElementById("gbp").textContent = data.results.GBP; document.getElementById("chf").textContent = data.results.CHF; }) .catch(error => { console.error("获取汇率失败:", error); alert("无法获取汇率数据,请检查API密钥或网络连接"); }); </script> </body> </html>
内容的提问来源于stack exchange,提问作者Kiran Sharma
相关产品推荐
相关产品推荐

