-1

I'm trying to build an exchange website and it's my first time working with APIs, I call a an asynchrounous function the moment a user types in an amount so that JS can get the selected currency and request it's equivalent in all the other currencies, but it gives me an error "Unexpected token < in JSON at position 0". Here is the html -

const select = document.querySelectorAll('option');

const form = document.querySelector('form');
const output = document.querySelector('.output');
const input = document.querySelector('.input');

const getExchangeRates = async(currency) => {
    const base = ' https://freecurrencyapi.net/api/v2/latest';
    const query = `?apikey=${key}&base_currency=${currency}`;
    const response = await fetch(base + query);
    const data = await response.json();
    return data.data;
}

const currencyOptions = (data) => {
    const currencies = Object.keys(data);
    for (let i = 0; i < currencies.length; i++) {
        select.forEach(option => {
            option.insertAdjacentHTML("afterend", `<option value="Select currency">${currencies[i]}</option>`)
        })
    }
}





getExchangeRates('EUR')
    .then(data => currencyOptions(data))
const selected = document.querySelector('select');




input.addEventListener('keyup', () => {
    getExchangeRates(selected.value);
})
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <link rel="stylesheet" href="/Curs.md/style.css">
    <style>
        body {
            color: #444;
        }
    </style>
</head>

<body>
    <form class="form-currency container mt-4 mb-4 text-align-center">
        <select name="selectCurrency" id="selectCurrency" class="form-select select-currency">
            <option value="Select currency" selected>Select currency</option>
        </select>
        <input type="text" name="input" class="input">
        <select name="selectCurrency" id="selectCurrency" class="form-select select-currency">
            <option value="Select currency" selected>Select currency</option>
        </select>
        <input type="text" name="output" class="output">
    </form>





    <script src="/Curs.md/Scripts/exchangeData.js"></script>
    <script src="/Curs.md/Scripts/app.js"></script>

</body>

</html>
  • 3
    The `<` part of the error-message is a dead-giveaway that your `fetch` request got HTML instead of JSON. You should always check the response's `Content-Type:` header says the response actually is JSON before calling `await resp.json()`, that way you can gracefully handle unexpected responses without the browser throwing an exception. – Dai Feb 19 '22 at 12:15
  • Also, you have whitespace at the start of your `base` string, which *might* be the problem: it'll mean it won't be interpreted as an absolute-URI, but as a page-relative URI. – Dai Feb 19 '22 at 12:16
  • Welcome to Stack Overflow! Please take the [tour] if you haven't already (you get a badge!), have a look around, and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) I also recommend Jon Skeet's [Writing the Perfect Question](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/) and [Question Checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Please [**search thoroughly**](/search?q=Unexpected+token+<+in+JSON+at+position+0) before posting. More about searching [here](/help/searching). – T.J. Crowder Feb 19 '22 at 12:23

1 Answers1

-1

It should be an issue of 404 Not being found or a server error from the API that you are calling.

Please try and reconfigure the API to solve this issue and make sure the API is returning JSON data.

  • The api is working just fine because even though it's not showing anything in the select options in the code snippet it actually works for me, so I'm sure the api is working just fine so that's why I asked the question. Do you have any other ideas why its showing this? – AlexzCoder Feb 19 '22 at 12:54
  • @AlexzCoder Remove the space character in-between the opening quote `'` and `https` in your `const base` string. – Dai Feb 19 '22 at 15:16