This question already has answers here:
No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API
(10 answers)
Closed last year.
I am attempting to read a csv form the source https://stats.oecd.org/Index.aspx?DataSetCode=WILD_LIFE.
Let x be the url above.
<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:
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.
Uncaught (in promise) TypeError: Failed to fetch
Is there a way around this block?
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);
?>
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.