在tomcat上启用CORS无法正常工作

时间:2018-08-02 00:13:47

标签: tomcat cors webserver

我在tomcat上托管了一个第三方Webapp(我无法对此Webapp进行代码更改)。最近,当我尝试在另一个具有不同域的网页上调用此Webapp的API时遇到了CORS问题。

我搜索了如何使tomcat启用,发现我可以将此设置添加到web.xml

<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
  <init-param>
    <param-name>cors.allowed.origins</param-name>
    <param-value>*</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.methods</param-name>
    <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.headers</param-name>
    <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
  </init-param>
  <init-param>
    <param-name>cors.exposed.headers</param-name>
    <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
  </init-param>
  <init-param>
    <param-name>cors.support.credentials</param-name>
    <param-value>true</param-value>
  </init-param>
  <init-param>
    <param-name>cors.preflight.maxage</param-name>
    <param-value>10</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

现在,进行一些简单的卷曲测试是可行的,但真正的CORS请求失败了。

简单的卷曲测试:

卷曲'http://127.0.0.1:8080/webapp/some/thing.htm'-X选项-H'来源:http://www.google.com'-v

这将返回带有CORS标头的响应,但是如果我尝试由chrome发送的CORS请求: 卷曲'http://127.0.0.1:8080/webapp/some/thing.htm'-X选项-H'访问控制请求方法:POST'-H'来源:http://www.google.com'-H'接受编码:gzip,deflate'- H'接受语言:en-US,en; q = 0.9'-H'用户代理:Mozilla / 5.0(Macintosh; Intel Mac OS X 10_10_5)AppleWebKit / 537.36(KHTML,如Gecko)Chrome / 67.0.3396.99 Safari /537.36'-H'接受: / '-H'代理连接:keep-alive'-H'访问控制请求头:access-control-allow-origin,内容类型'--compressed -v

奇怪的是,如果我删除“ -H'访问控制请求方法:POST'”或“ -H'访问控制请求请求头:访问-control-allow-origin,content-type'“,它将返回有效的CORS响应,但是命令上同时包含两个标头,它将失败

0 个答案:

没有答案