创建地图时同源策略错误

same origin policy error when creating map

我尝试了 运行 下面使用 OpenLayers 创建地图的代码。该代码是 GeoServer Beginner's Guide.

中的示例

该代码创建了一个地图并向其添加了几个图层。客户端代码(下方)从本地文件系统加载,图层数据从 Geoserver 运行 本地下载到 post 8080.

该代码应该创建一个地图并向其添加几个图层。第二层由addGeoRSS函数添加。第一层添加成功,但是添加第二层失败,出现如下错误

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/geoserver/tiger/wms?service=WMS&version=1.1.0&request=GetMap&layers=tiger:poi&styles=&bbox=-74.0118315772888,40.70754683896324,-74.00153046439813,40.719885123828675&width=427&height=512&srs=EPSG:4326&format=application%2Frss%2Bxml. This can be fixed by moving the resource to the same domain or enabling CORS.

鉴于两层都是从同一台主机下载的,我预计它们都会失败,为什么只有第二层会导致问题?

var GEOSERVERBASE = "http://localhost:8080";
var CountyLayer = 'tiger:tl_2011_us_county';
var map;

function mapinitialize() {

    map = new OpenLayers.Map('map', {
        maxResolution:'auto',
        projection: 'EPSG:4326'
    });
    layer = new OpenLayers.Layer.WMS(
        CountyLayer, GEOSERVERBASE + "/geoserver/tiger/wms",
        {
            layers: CountyLayer,
            format: 'image/png'
        }
    );

    // first (successful) request to Geoserver running at http://localhost:8080
    map.addLayer(layer);
    map.zoomTo(9);
    map.panTo(new OpenLayers.LonLat(-73.99, 40.75)); 

    // second request to Geoserver that causes a CORS error
    addGeoRSS();
}

function addGeoRSS() {

    var value = GEOSERVERBASE + '/geoserver/tiger/wms?service=WMS&version=1.1.0&request=GetMap&layers=tiger:poi&styles=&bbox=-74.0118315772888,40.70754683896324,-74.00153046439813,40.719885123828675&width=427&height=512&srs=EPSG:4326&format=application%2Frss%2Bxml';
    var georss = new OpenLayers.Layer.GeoRSS('Tiger POI', value);
    map.addLayer(georss);
}

您的第一层请求是针对图像 (.png) 并且图像不受 CORS 限制。然而,CORS 错误的原因仍然是您使用 file:// 加载客户端代码,然后尝试使用 http://

加载(非图像)资源