GeoServer配置CORS(跨域资源共享)

时间:2021-10-16 18:00:38

当前台页面请求WMS可能会遇到浏览器以下提示(浏览器控制台):

已阻止跨源请求:同源策略禁止读取位于 http://xxx.xxx.com 的远程资源。(原因:CORS 头缺少 'Access-Control-Allow-Origin')

原文大概这样

Access to Image at 'http://192.168.0.131:8080/geoserver/CHINA/wms?SERVICE=WMS&VERSION=1.1.1&REQ…AT_OPTIONS=dpi%3A99&BBOX=-20037508.342789244%2C-20037508.342789244%2C0%2C0' 
from origin 'http://localhost:59307' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:59307' is therefore not allowed access. The response had HTTP status code 404.

贴个图更形象一些

GeoServer配置CORS(跨域资源共享)

网上找到的大部分CORS配置都是针对GeoServer 安装版的 像 基于CORS的geoserver同源访问策略 这样的

因为我事先已经有Tomcat了,所以用的是解压版本的GeoServer 。(贴上搭建环境的连接: 搭建简易Web GIS网站:使用GeoServer+PostgreSQL+PostGIS+OpenLayers3

找到的方法无法实现,只能寻找其他办法,那就是针对Tomcat的 CORS

首先需要下载cors-filter-1.7.jar,java-property-utils-1.9.jar这两个jar包,放到Tomcat 的  lib目录下。

我的路径是 D:\Program Files (x86)\ApacheTomcat\lib

(也可在http://search.maven.org上查询并下载。)

下载地址

然后 找到你须需要配置CORS的应用的路径(也就是我的 geoserver)

D:\Program Files (x86)\ApacheTomcat\webapps\geoserver                  

然后找到 WEB-INF 下面的 web.xml  在filter集合末尾额外添加如下配置

<filter>
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
<init-param>
<param-name>cors.allowOrigin</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.supportedMethods</param-name>
<param-value>GET, POST, HEAD, PUT, DELETE</param-value>
</init-param>
<init-param>
<param-name>cors.supportedHeaders</param-name>
<param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified</param-value>
</init-param>
<init-param>
<param-name>cors.exposedHeaders</param-name>
<param-value>Set-Cookie</param-value>
</init-param>
<init-param>
<param-name>cors.supportsCredentials</param-name>
<param-value>true</param-value>
</init-param>
</filter> <filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

然后重启geoserver 就好了