从我的本地机器(主机).js & .html 调用外部 API

Call external API from my local machine (host) .js & .html

因为这是我的第一个 post 请保持温柔 ;)。请注意,我是编程新手,所以我可能会问有线问题,反之亦然,请确认您的答案,如果包含许多缩写词或思维捷径,我可能很难理解。

我尝试从我的本地机器调用 API。我使用 MAC、Chrome v78、VSC。

我有以下代码:

window.addEventListener("load", ()=> {
var long;
var lat;

if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(position => {
        console.log(position);
        long = position.coords.longitude;
        lat = position.coords.latitude;
        console.log(long, lat);

        const proxy = 'https://cors-anywhere.herokuapp.com/';
        const api = '${proxy}https://api.darksky.net/forecast/c8896cdad78b43417e8fb2969fbc5d21/37.8267,-122.4233';

        fetch(api)
            .then(response => response.json())
            .then(json => console.log(json))
    });
}

});

不幸的是,我在控制台中得到的是 404 错误:

GET http://127.0.0.1:5500/APP/$%7Bproxy%7Dhttps://api.darksky.net/forecast/c8896cdad78b43417e8fb2969fbc5d21/37.8267,-122.4233 404 (Not Found)

为什么它也调用127.0.0.1:5500?我怎么能省略呢?

您使用了常规字符串(单引号或双引号)而不是模板字符串(反引号)来替换代理变量,导致 ${proxy} 部分无法替换为“https://cors-anywhere.herokuapp.com/”。

浏览器将请求发送到“127.0.0.1:5500”,因为“${proxy}https://api.darksky.net/forecast/c8896cdad78b43417e8fb2969fbc5d21/37.8267,-122.4233”不是以 http:// 或 https:// 开头(而是以 ${proxy}所以请求被发送到当前来源,即“127.0.0.1:5500”(您的开发网站暴露的地方)。

解决方案

const api = `${proxy}https://api.darksky.net/forecast/c8896cdad78b43417e8fb2969fbc5d21/37.8267,-122.4233`;