【问题标题】:fetch error No 'Access-Control-Allow-Origin' header is present on the requested resource获取错误请求的资源上不存在“Access-Control-Allow-Origin”标头
【发布时间】:2017-10-05 02:10:14
【问题描述】:

我正在使用 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)) 不会在控制台中记录任何内容,并且 fetch 不会返回任何值。 我的代码有什么问题?

【问题讨论】:

标签: javascript fetch fetch-api


【解决方案1】:

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

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

【讨论】:

【解决方案2】:

在 url 后使用“no-cors”参数时不会出现此问题

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

【讨论】:

  • 我试过你的代码,但我的回复会返回空,我不知道为什么会这样,你能给我你的反馈吗?
  • 说这可以“修复”任何事情都是误导。这一切所做的只是给你一个空洞的响应而不是一个错误,不管它值多少钱。 @huykon225 见stackoverflow.com/a/35291777/6221448
  • 请注意,mode: "no-cors" 只允许请求中包含一组有限的标头。因此,例如,您不能使用“授权”标头。 Source
猜你喜欢
  • 2015-05-30
  • 2016-05-20
  • 2015-07-29
  • 1970-01-01
  • 2017-12-16
  • 2016-11-25
  • 2015-04-04
  • 1970-01-01
相关资源
最近更新 更多