没有“访问控制允许来源":读取CSV,D3 [英] No 'Access-Control-Allow-Origin': Reading CSV, D3

查看:176
本文介绍了没有“访问控制允许来源":读取CSV,D3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从源代码 https://stats.oecd中读取csv. .org/Index.aspx?DataSetCode = WILD_LIFE .

I am attempting to read a csv form the source https://stats.oecd.org/Index.aspx?DataSetCode=WILD_LIFE.

让x作为上面的网址.

 <script type="text/javascript">  
  var data_threatened = d3.csv(x)
   .then(function(data){
    console.log(data);
  })  
  </script>

但是,当我在本地主机上运行此脚本时,会收到以下消息:

However, when I run this script on my local host, I receive the following message:

访问地址为 ' https://stats.oecd.org/Index.aspx?DataSetCode=WILD_LIFE'起源 ' http://localhost:8888 '已被CORS政策阻止:否 请求中存在"Access-Control-Allow-Origin"标头 资源.如果不透明的响应满足您的需求,请设置请求的 模式设置为"no-cors",以在禁用CORS的情况下获取资源.

Access to fetch at 'https://stats.oecd.org/Index.aspx?DataSetCode=WILD_LIFE' from origin 'http://localhost:8888' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

未捕获(承诺)TypeError:无法获取

Uncaught (in promise) TypeError: Failed to fetch

有没有办法解决这个问题?

Is there a way around this block?

推荐答案

获取文件并从与脚本运行时相同的来源提供文件是最容易的.例如. PHP不太关心CORS(假设此文件有时会更改).万一它没有变化,甚至手动将其放置就足够了.

Fetching the file and serving it from the same origin as the script runs would be the most easy. eg. PHP cares little about CORS (assuming that this file occasionally changes). In case it doesn't change, even manually placing it there would suffice.

要让服务器端脚本获取文件,然后将其用作同源文件,而不进行缓存:

To let a server-side script fetch the file and then serve it as same-origin, without caching it:

<?php
    $url = "https://stats.oecd.org/Index.aspx?DataSetCode=WILD_LIFE";
    header("Content-type: text/csv");
    echo file_get_contents($url);
?>

任何服务器端脚本语言都应该能够做到;我使用PHP只是为了提供示例.可以将WILD_LIFE设置为变量,以便将其用于获取任何数据集.

Any server-side scripting language should be capable of doing so; I used PHP just to provide an example. One could make WILD_LIFE a variable, so that it could be used to fetch any data-set.

这篇关于没有“访问控制允许来源":读取CSV,D3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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