获取错误请求的资源上没有“Access-Control-Allow-Origin”标头 [英] fetch error No 'Access-Control-Allow-Origin' header is present on the requested resource

查看:151
本文介绍了获取错误请求的资源上没有“Access-Control-Allow-Origin”标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using fetch API to get data from other APIs this is my code:

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

但我在控制台中遇到错误:

but I face error in console:

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.

我为第二次获取设置了标题:

I set headers for the second fetch:

return fetch(`https://api.darksky.net/forecast/efc76f378da9a5bd8bb366a91ec6f550/${lat},${lon}`, {
  mode: 'no-cors',
  header: {
    'Access-Control-Allow-Origin':'*',
  }
}); 

错误将消失,但 console.log(JSON.stringify(data)) 不要在控制台中记录任何内容,并且fetch不会返回任何值。
我的代码有什么问题?

error will gone but console.log(JSON.stringify(data)) do not log anything in console and the fetch not return any value. what is the problem with my code?

推荐答案

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

The problem is not in your JavaScript code, it is in the API, the server doesn't support cross origin request, if you are the owner of this API you have to add 'Access-Control-Allow-Origin' header to the response with the allowed origins (* to allow from any origin). in some cases jsonp request may work.

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

Note: this problem happen only when the request is generated from the browser

这篇关于获取错误请求的资源上没有“Access-Control-Allow-Origin”标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆