0

The error is as such:

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

Current code:

window.addEventListener('load', () => {
    const locatoin = document.querySelector('#location');
    const tempNum = document.querySelector('#temp');
    const description = document.querySelector('#description');
    const APIkey = 'myAPIkeyHere';
    var lat;
    var long;
    var currentPos;
    
    if (navigator.geolocation) {
        currentPos = navigator.geolocation.getCurrentPosition(position => {
            lat = position.coords.latitude;
            long = position.coords.longitude;
        });

        const api = `api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${APIkey}`;
        fetch(api)
            .then(response => {
                return response.json();
            })
            .then(data => {
                console.log(data);
            })
        }
})

function refresh() {
    location.reload();
}

I do not get any errors up until then and if I manually search the API url request it gives me the json data.

Thanks.

Fin HARRIS
  • 118
  • 10
  • 1
    Does this answer your question? ["SyntaxError: Unexpected token < in JSON at position 0"](https://stackoverflow.com/questions/37280274/syntaxerror-unexpected-token-in-json-at-position-0) – Ivar Sep 26 '20 at 16:24
  • The call to your API is most likely returning HTML instead of JSON. Change `return response.json()` to `return response.text()` and see what it actually returns. – Ivar Sep 26 '20 at 16:24
  • Check the assertions. So simple: *use the developer tools to inspect the actual response*. Fix it. – user2864740 Sep 26 '20 at 16:49

1 Answers1

0

You need to update the api url. It should be start with https/http depend on server so that you will get json response rather than html.

const api = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${APIkey}`;
deepak
  • 1,390
  • 1
  • 8
  • 12
  • This hypothetical issue — failure of the server to return any data — won’t cause that error. The error is _only_ cause when the first character of the response is `<` – user2864740 Sep 26 '20 at 16:50