簡體   English   中英

檢索 JSON api 數據時出錯:Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

[英]Error when retrieving JSON api data: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

錯誤是這樣的:

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

當前代碼:

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();
}

在那之前我沒有收到任何錯誤,如果我手動搜索 API url 請求,它會給我 json 數據。

謝謝。

您需要更新 api 網址。 它應該以 https/http 開頭,取決於服務器,這樣您將獲得 json 響應而不是 html。

const api = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${APIkey}`;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM