Search code examples
javascriptsame-origin-policy

same origin policy error when creating map


I tried running the code below that creates a map using OpenLayers. The code is an example from the GeoServer Beginner's Guide.

The code creates a map and adds a couple of layers to it. The client-side code (below) is loaded from the local filesystem and the layer data is downloaded from Geoserver running locally on post 8080.

The code is supposed to create a map and add a couple of layers to it. The second layer is added by the addGeoRSS function. The first layer is added successfully, but adding the second layer fails with the following error

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.

Given that both layers are downloaded from the same host, I would expect both of them to fail, why does only the second one cause problems?

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

Solution

  • Your first layer request is for an image (.png) and images are not subject to CORS restrictions. The reason for the CORS error, however, remains the fact that you're loading client code with file:// and then trying to load a (non-image) resource with http://