[GIS] Getting WFS layer from GeoServer to OpenLayers 3

geoserverjavascriptopenlayerswfs

I am creating a web map application for a website. I am using GeoServer 2.6.2 and OpenLayers 3.2. I have not problems with WMS layers, but I am not be able to visualize vector layers. This is the javascript code that I have added (I followed this OpenLayers example and this other example):

var vector2Source = new ol.source.ServerVector({
  format: new ol.format.GeoJSON(),
  loader: function(extent, resolution, projection) {
    var url = 'http://localhost/geoserver/Workspace/wfs?service=WFS&' +
        'version=1.1.0&request=GetFeature&typename=Workspace:Polygon&' +
        'outputFormat=json' + '&srsname=EPSG:6823&bbox=' + extent.join(',') + ',EPSG:3857';
    $.ajax(url).then(function(response){
        vector2Source.addFeatures(vector2Source.readFeatures(response));
    });
},
strategy: ol.loadingstrategy.createTile(new ol.tilegrid.XYZ({
    maxZoom:19
  }))
  //projection: "EPSG:6823"
});


var vector2 = new ol.layer.Vector({
  source: vector2Source,
  style: new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: 'rgba(0, 0, 255, 1.0)',
      width: 2
    })
  })
});

The browser (google chrome) shows me the following error:

XMLHttpRequest cannot load http://localhost/geoserver/Workspace/wfs?service=WFS&vers…7148101,1526294.5807983987,-9920914.775189597,1536078.5204189012,EPSG:3857. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

Could someone help me?

Best Answer

If GeoServer is served under a different domain to your page then you will need to either enable CORS on the GeoServer application server or enable JSONP requests in GeoServer and update your OL3 app to send JSONP requests.

Some of this is covered here under "Cross-domain requests": http://astuntechnology.github.io/osgis-ol3-leaflet/ol3/03-GEOJSON-INFO.html