Access-Control-Allow-Origin不允许使用原点null。

csn*_*ake 5 d3.js

当我运行以下代码时:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>D3 Demo: GeoJSON</title>
        <script type="text/javascript" src="http://localhost/webserver/d3/d3.js"></script>
        <style type="text/css">
            /* No style rules here yet */       
        </style>
    </head>
    <body>
        <script type="text/javascript">

            //Width and height
            var w = 500;
            var h = 300;

            //Define default path generator
            var path = d3.geo.path();

            //Create SVG element
            var svg = d3.select("body")
                        .append("svg")
                        .attr("width", w)
                        .attr("height", h);

            //Load in GeoJSON data
            d3.json("http://localhost/webserver/us-states.json", function(json) {

                //Bind data and create one path per GeoJSON feature
                svg.selectAll("path")
                   .data(json.features)
                   .enter()
                   .append("path")
                   .attr("d", path);

            });

        </script>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

XMLHttpRequest cannot load http://localhost/webserver/us-states.json. Origin null is not allowed by Access-Control-Allow-Origin. 
Run Code Online (Sandbox Code Playgroud)

这里出了什么问题,我该如何解决?我正在关注Scott Murray的书,到目前为止,在我开始使用json之前,访问网络服务器上的文件一直没有问题。

And*_*tos 7

出于安全原因,浏览器会阻止来自不同主机(来源)的 Ajax HTTP 请求 (XHR)。

d3.json("...")函数向您的http://localhost/ ...发出 Ajax 请求,并且您可能正在从不同的主机提供 HTML。

您是否在浏览器中打开 .html 作为文件?那被认为是不同的主机。你有一些选择:

  • 从您为 json 文件提供服务的同一 Web 服务器提供您的 HTML 文件
  • 将您的 .json 转换为 .js var mygeodata = {your json here},在文件中添加类似内容并<script type="text/javascript" src="http://localhost/webserver/us-states.js"></script>在 HTML 中添加内容,<head>同时删除该d3.json("...")部分。之后,您有一个包含数据的全局变量mygeodata
  • 配置您的 Web 服务器以允许 CORS。

如果您正在研究/原型(从外观上看),我会采用第二种方法。