Geoserver 2.13.0 跨域请求 ‘Access-Control-Allow-Origin’ 问题

使用leaflet请求GeoServer发布的WFS服务时,如果不是相同的域可能会出现如下问题:

Failed to load http://192.168.0.126:8080/geoserver/ows?service=wfs&version=1.0.0&request=GetCapabilities: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:8080’ is therefore not allowed access. The response had HTTP status code 503.

网上查到的答案都是要自己”下载geoserver使用的对应jetty版本”,然而根本找不到Geoserver 2.13 对应的版本说明,偶然在Geoserver安装目录中找到了jetty-servlets.jar。

解决方法如下:

1. 添加跨域jar包jetty-servlets.jar。

<Geoserver>\lib目录下会有jetty-servlets.jar

D:\Program Files (x86)\GeoServer 2.13.0\lib

并将jar包放到<Geoserver>\webapps\geoserver\WEB-INF\lib文件夹下。
D:\Program Files (x86)\GeoServer 2.13.0\webapps\geoserver\WEB-INF\lib

2. 修改<Geoserver>\webapps\geoserver\WEB-INF\web.xml文件。

D:\Program Files (x86)\GeoServer 2.13.0\webapps\geoserver\WEB-INF\web.xml

找到文件中<filter>平级的位置,添加如下内容:

<filter>
    <filter-name>cross-origin</filter-name>
    <filter-class>org.eclipse.jetty.servlets.CrossOriginFilter</filter-class>
    <init-param>
        <param-name>allowedOrigins</param-name>
        <param-value>*</param-value>
    </init-param>
    <init-param>
        <param-name>allowedMethods</param-name>
        <param-value>GET,POST</param-value>
    </init-param>
    <init-param>
        <param-name>allowedHeaders</param-name>
        <param-value>x-requested-with,content-type</param-value>
    </init-param>
</filter>

filter-mapping设置

找到文件中<filter-mapping>平级的位置,添加如下内容:

<filter-mapping>
   <filter-name>cross-origin</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

参考链接:
geoserver地图跨域解决方案
找到的OpenLayers跨域访问WFS服务出现No ‘Access-Control-Allow-Origin’ header is present…错误的一种解决办法
No ‘Access-Control-Allow-Origin’ header is present on the requested resource.’Ajax跨域访问解决方案
从前端和后端两个角度分析jsonp跨域访问(完整实例)

转载自:https://blog.csdn.net/neimeng0/article/details/80094333

You may also like...