[英]Enabling a CORS Response Filter in Tomcat 8.0
我試圖使用一個相當基本的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"
});
我總是得到以下error
響應...
XMLHttpRequest無法加載http://dev.hostname.com/ws/account/example1@example.com?property_id=1&custnum=123456 。 請求的資源上不存在“Access-Control-Allow-Origin”標頭。 原因
http://localhost:63342
因此不允許訪問。
Web服務是在Apache Tomcat/8.0.8
上托管的基於Java構建的基於Jersey的Web服務。 我嘗試將請求作為JSONP發送,但在嘗試處理promise對象的回調時遇到了問題。 那是另一篇文章......作為替代方案,我決定考慮實施CORS Response解決方案。 現在我對Java編程非常陌生,對它不太滿意所以請耐心等待。
我已經看了兩個實現CORS的主要解決方案。 一種是構建自定義響應過濾器。 我無法讓它工作但后來發現,因為Tomcat 7.0已經提供過濾器了。 我已經看到了第二個解決方案的幾個帖子,但絕對沒有運氣。 使用Apache Tomcat文檔中提供的指南,我將以下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的頭文件。 這是Request標頭......
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
這是Response標頭
Content-Length 0
Content-Type text/plain
Date Thu, 21 Aug 2014 17:50:58 GMT
Server Apache-Coyote/1.1
我絕對沒有看到任何期望在響應中看到的“Access-Control- *”標題。
這里提供的CORS配置對我有用,但直到我在最后一個標題中的逗號后面的'Allowed Headers'中刪除了空格。
<param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers, Last-Modified</param-value>
一旦我在“Last-Modified”之前取出那個空間,我就開始了。
在運行Apache Tomcat / 8.0.43的傳統Struts 2應用程序中修復此問題的解決方案是在web.xml
配置文件中的Struts 2過濾器之前添加CORS過濾器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.