JS
(function onLoad()
{
// set a function for each button
setButtonFunctions();
// fetch from each API when the page loads
getCurrencyExchangeRates();
})();
function setButtonFunctions()
{
document.getElementById('buttonCurrency').onclick = getCurrencyExchangeRates;
}
// Currency Exchange rates
async function getCurrencyExchangeRates()
{
const from = document.getElementById('inputCurrencyFrom').value;
const to = document.getElementById('inputCurrencyTo').value;
await fetch("https://currency-exchange.p.rapidapi.com/exchange?q=1.0&from=" + from + "&to=" + to, {
"method": "GET",
"headers": {
"x-rapidapi-host": "currency-exchange.p.rapidapi.com",
"x-rapidapi-key": "f99358f04amshb8ab13c184cbf53p157a7ejsn19909cd7c96e"
}
})
.then(response => response.json())
.then(response => {
console.log("Currency Exchange API object:");
console.log(response);
console.log("\n");
// display data
document.getElementById('currencyResult').innerHTML = 'Result: ' + response;
})
.catch(err => {
console.log(err);
});
}
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>API examples</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="./css/style.css">
</head>
<body>
<!-- Currency exchange rates -->
<div class="display-4 text-center">Currency exchange rates</div>
<div class="APIContainer">
<h4>Find out current currency exchange rates</h4>
<div class="currencyContainer">
<div style="margin-top: 16px">
<p>From: </p>
<p>To: </p>
</div>
<div style="margin-left: 20px">
<input class="form-control marginTopBottom" type="text" id="inputCurrencyFrom" value="EUR">
<input class="form-control marginTopBottom" type="text" id="inputCurrencyTo" value="USD">
<button class="btn btn-primary" id="buttonCurrency">Calculate</button>
</div>
<div class="currencyResult">
<h4 id="currencyResult">Result: 0</h4>
</div>
</div>
</div>
<script src="./js/main.js" type="module"></script>
</body>
</html>
В консоли браузера этот код идеально работает
const options = { method: 'GET',
headers: {
'X-RapidAPI-Key': 'f99358f04amshb8ab13c184cbf53p157a7ejsn19909cd7c96e',
'X-RapidAPI-Host': 'currency-exchange.p.rapidapi.com'
}
};
fetch('https://currency-exchange.p.rapidapi.com/exchange?from=SGD&to=MYR&q=1.0', options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));