I am fetching an exchange rates API. The API looks like this: https://v6.exchangerate-api.com/v6/Your-Api-Key/latest/AMD, where "Your-API-Key" is my personal key. If the API URL ends with USD or AMD, the API recognises the base currency as USD or AMD and then gives the exchange rate in other currencies, including the base currency.
For example:
HTML:
<select name="BaseCurrency" id="BaseCurrency">
<option value="NGN">NGN</option>
<option value="USD">USD</option>
<option value="ALL">ALL</option>
</select>
JavaScript code:
async function fetchCurrencyData() {
let baseCurrencyValue = document.getElementById("BaseCurrency").value;
console.log(baseCurrencyValue) // logs selected HTML option value, say "NGN" or "USD", based on user selection.
let result = await fetch(`https://v6.exchangerate-api.com/v6/My-Api-Key/latest/${baseCurrencyValue}`);
let record = await result.json();
console.log("Hey " + JSON.stringify(record.conversion_rates.baseCurrencyValue)); //This logs "Hey undefined" but when I replace baseCurrencyValue with an actual currency code, like USD, it prints out the correct rate"
What can I do to make sure that concatenating the variable "baseCurrencyValue" at the end of the API, will work? Because I need to allow the user's choice to be the base currency
I have also tried concatenating with the plus sign:
let result = await fetch("https://v6.exchangerate-api.com/v6/My-Api-Key/latest/" + baseCurrencyValue);
But it isn't working either.
You ensure that it will work by controlling what inputs you accept. Also I noticed that there is a CORS issue with this API, which can be fixed with corsAnywhere. Ideally you should be calling external APIs on your backend not your frontend.
<select name="BaseCurrency" id="base-currency">
<option value="NGN">NGN</option>
<option value="USD">USD</option>
<option value="ALL">ALL</option>
</select>
<button onclick="fetchCurrencyData()">click</button>
<script>
async function fetchCurrencyData() {
const baseCurrencyValue = document.getElementById('base-currency').value;
const result = await fetch(
`https://cors-anywhere.herokuapp.com/https://v6.exchangerate-api.com/v6/APIKEYHERE/latest/${baseCurrencyValue}`
);
const { conversion_rates } = await result.json();
console.log(conversion_rates);
}
</script>