各種新版本的ie10,firefox,opera,safari,chrome以及移動版safari和 android瀏覽器
ie9及一下版本請使用flash方式來兼容
通過OPTIONS請求握手一次的方式實現跨根域發送請求,需要服務端配置
nginx增加類似如下配置:
- server {
- location / {
- if ($ request_method = ‘OPTIONS’) {
- add_header ‘Access-Control-Allow-Origin’ ‘*’;
- add_header ‘Access-Control-Allow-Credentials’ ‘true’;
- add_header ‘Access-Control-Allow-Methods’ ‘GET, POST, OPTIONS’;
- add_header ‘Access-Control-Allow-Headers’ ‘DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type’;
- # add_header ‘Access-Control-Max-Age’ 1728000;
- add_header ‘Content-Type’ ‘text/plain charset= UTF-8′;
- add_header ‘Content-Length’ 0;
- return 200;
- }
- }
如果沒有nginx轉發, java需要如下代碼
- rundata.getResponse().addHeader(“Access-Control-Allow-Origin”, “*”);
- rundata.getResponse().addHeader(“Access-Control-Allow-Methods”, “GET, POST, OPTIONS”);
- rundata.getResponse().addHeader(“Access-Control-Allow-Headers”, “Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With”);
tomcat下CORS( 跨域資源共享) 的配置
CORS介紹
它在維基百科上的定義是: 跨域資源共享(CORS )是一種網絡瀏覽器的技術規範,它爲Web服務器定義了一種方式,允許網頁從不同的域訪問其資源。而這種訪問是被同源策略所禁止的。CORS系統定義了一種瀏覽器和服務器交互的方式來確定是否允許跨域請求。
它是一個妥協,有更大的靈活性,但比起簡單地允許所有這些的要求來說更加安全。
而W3C的官方文檔目前還是工作草案,但是正在朝着W3C推薦的方向前進。
簡言之,CORS就是爲了讓AJAX可以實現可控的跨域訪問而生的。
http://search.maven.org上查詢並下載。)工程項目中web.xml中的配置如下:
<?xml version="1.0" encoding="UTF-8"?>
-
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>service.print.cloud</display-name>
<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>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
兼容情況:
各種新版本的ie10,firefox,opera,safari,chrome以及移動版safari和 android瀏覽器