Javascript 获取错误号';访问控制允许原点';请求的资源上存在标头

Javascript 获取错误号';访问控制允许原点';请求的资源上存在标头,javascript,fetch,fetch-api,Javascript,Fetch,Fetch Api,我正在使用fetch API从其他API获取数据这是我的代码: var result = fetch(ip, { method: 'get', }).then(response => response.json()) .then(data => { country = data.country_name; let lat = data.latitude; let lon = data.longitud

我正在使用fetch API从其他API获取数据这是我的代码:

var result = fetch(ip, {
        method: 'get',
    }).then(response => response.json())
      .then(data => {
        country = data.country_name;
        let lat = data.latitude;
        let lon = data.longitude;                       
        //fetch weather api with the user country
        return fetch(`https://api.darksky.net/forecast/efc76f378da9a5bd8bb366a91ec6f550/${lat},${lon}`);
    })
    .then(response => response.json())
    .then(data => {
        // access the data of the weather api
        console.log(JSON.stringify(data))
    })
    .catch(error => console.log('Request failed', error));
但我在控制台中面临错误:

Fetch API cannot load https://api.darksky.net/forecast/efc76f378da9a5bd8bb366a91ec6f550/52.3824,4.8995. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
我为第二次提取设置了标题:

return fetch(`https://api.darksky.net/forecast/efc76f378da9a5bd8bb366a91ec6f550/${lat},${lon}`, {
  mode: 'no-cors',
  header: {
    'Access-Control-Allow-Origin':'*',
  }
}); 
错误将消失,但
console.log(JSON.stringify(data))
不在控制台中记录任何内容,并且获取不会返回任何值。
我的代码有什么问题?

问题不在JavaScript代码中,而是在API中,服务器不支持跨源请求,如果您是此API的所有者,则必须使用允许的源(*允许来自任何源)将'Access-Control-Allow-origin'头添加到响应中。 在某些情况下,jsonp请求可能会起作用


注意:只有当从浏览器生成请求时,才会出现此问题。

可以通过在url后面使用“no cors”参数来解决此问题

fetch(url, {mode: "no-cors"})

这对我来说也是正确的答案。另一个答案给出了您可以使用的特定CORS头的一些详细信息:我尝试了您的代码,但我的响应将返回空,我不知道为什么会出现这种情况,您能给我您的反馈吗?说这可以“修复”任何东西是误导的。所有这些都会给你一个空的响应,而不是一个错误,不管它值多少钱@惠康225见