我正在尝试使用相当基本的 jQuery.ajax
POST 请求从另一台服务器(跨源)调用 Web 服务。
return $.ajax({
type: "POST",
url: "http://dev.hostname.com/ws/account/example1@example.com?property_id=1&custnum=123456",
dataType:"json"
});
我总是收到以下错误
响应...
XMLHttpRequest cannot load http://dev.hostname.com/ws/account/example1@example.com?property_id=1&custnum=123456. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin
http://localhost:63342
is therefore not allowed access.
Web 服务是一个基于 Jersey 的 Java 构建的 Web 服务,托管在 Apache Tomcat/8.0.8
上。我曾尝试将请求作为 JSONP 发送,但在尝试处理来自 promise 对象的回调时遇到了问题。然而,这是另一篇文章......作为替代方案,我决定研究实现 CORS 响应解决方案。现在我对 Java 编程还很陌生,对它不太满意,所以请多多包涵。
我研究了两种实现 CORS 的主要解决方案。一种是构建自定义响应过滤器。我无法让它工作,但后来发现自 Tomcat 7.0 以来,据说已经提供了一个过滤器。我已经看过关于第二个解决方案的几篇文章,但绝对没有运气。使用 Apache Tomcat Documentation 中提供的指南,我将以下 FILTER 信息添加到应用程序的 web.xml 文件中(我也尝试将它添加到根目录的 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, Last-Modified</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>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
因为我使用的是 Tomcat 8.0.8
。我本以为这会起作用,但我仍然遇到同样的错误。我错过了什么吗?
感谢您的帮助。
已更新
在 Firefox 中调用服务时,我正在添加来自 Firebug 的 header 。这是请求 header ......
Accept application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Cache-Control no-cache
Connection keep-alive
Content-Length 0
Host dev.hostname.com
Origin http://localhost:63342
Pragma no-cache
Referer http://localhost:63342/keurig/default.html
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0
这是响应头
Content-Length 0
Content-Type text/plain
Date Thu, 21 Aug 2014 17:50:58 GMT
Server Apache-Coyote/1.1
我绝对没有看到任何期望在响应中看到的“Access-Control-*” header 。
最佳答案
此处提供的 CORS 配置对我有用,但直到我删除了最后一个 header 中逗号后的“允许 header ”中的空格。
<param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers, Last-Modified</param-value>
一旦我在“Last-Modified”之前取出那个空间,我就开始工作了。
关于java - 在 Tomcat 8.0 中启用 CORS 响应过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25442115/