如何使用 ExchangeRate-API 获取货币汇率
如果你需要获取货币的汇率信息,你可以使用第三方的货币汇率API。以下是一个使用 ExchangeRate-API 的示例:
const fetch = require('node-fetch');
// 设置请求参数
const baseCurrency = 'USD'; // 基准货币
const targetCurrency = 'CNY'; // 目标货币
const apiKey = 'YOUR_API_KEY'; // 在 ExchangeRate-API 注册并获取 API 密钥
// 构建 API 请求 URL
const apiUrl = `https://v6.exchangeratesapi.io/latest?base=${baseCurrency}&symbols=${targetCurrency}&access_key=${apiKey}`;
// 发送 HTTP 请求
fetch(apiUrl)
.then(response => response.json())
.then(data => {
// 提取汇率信息
const exchangeRate = data.rates[targetCurrency];
console.log(`1 ${baseCurrency} = ${exchangeRate} ${targetCurrency}`);
})
.catch(error => {
console.error('Error:', error);
});
上述代码使用 ExchangeRate-API 来获取美元(USD)和人民币(CNY)之间的汇率。你需要在 YOUR_API_KEY 处填入你在 ExchangeRate-API 注册并获得的 API 密钥。通过解析 API 的响应数据,我们可以提取出汇率信息并进行处理。
请注意,此示例中使用了 node-fetch 库来进行 HTTP 请求。在实际使用中,你可能需要根据不同的环境和框架来选择适当的 HTTP 请求库。
如果你需要其他关于货币的操作或有其他问题,请随时提问。
原文地址: https://www.cveoy.top/t/topic/bJ8r 著作权归作者所有。请勿转载和采集!