REQUEST:
OPTIONS /resources/l.jsp HTTP/1.1
Host: localhost:18086
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36
Access-Control-Request-Headers: accept, x-requested-with, content-type
Accept: */*
Referer: http://localhost:8080/static/product/ProductInput.html?wef11ssss
Accept-Encoding: gzip,deflate,sdch
Accept-Language: zh-CN,zh;q=0.8,en;q=0.6
RESPONSE :
HTTP/1.1 200 OK
Date: Thu, 16 Oct 2014 09:44:35 GMT
Access-Control-Allow-Origin: http://localhost:8080
Access-Control-Allow-Credentials: true
Vary: Origin
Access-Control-Allow-Methods: POST, GET, OPTIONS, HEAD
Access-Control-Allow-Headers: accept, x-requested-with, content-type
Content-Length: 0
Server: Jetty(9.3.0.M0)
跨域请求时:浏览器会首先发送一个请求,目标服务返回是否允许访问:
request 会带有:
OPTIONS /resources/l.jsp HTTP/1.1
Access-Control-Request-Method: POST //请求的参数
Origin: http://localhost:8080 //请求来源域
Access-Control-Request-Headers: accept, x-requested-with, content-type //真正请求时
允许 跨域请求则返回:
Access-Control-Allow-Origin: http://localhost:8080 //允许请求的域来源
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: POST, GET, OPTIONS, HEAD //允许请求的方法
Access-Control-Allow-Headers: accept, x-requested-with, content-type//允许请求时的header
浏览器接到返回数据后,才会发送实际请求。
服务器需要能够处理跨域请求,返回对应的header.
cors-filter 是一个Filter ,参够实现服务端的cors功能。
jar包下载地址:http://software.dzhuvinov.com/cors-filter.html
配置:
web.xml:
<filter>
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
<init-param>
<param-name>cors.supportedMethods</param-name>
<param-value>GET, POST, HEAD, PUT, DELETE</param-value>
</init-param>
<init-param>
<param-name>cors.maxAge</param-name>
<param-value>3600</param-value><!--单位秒-->
</init-param>
<init-param>
<param-name>cors.exposedHeaders</param-name>
<param-value>Content-Range</param-value><!--允许客户端js访问的header-->
</init-param>
</filter>
<filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
详细配置见:http://software.dzhuvinov.com/cors-filter-configuration.html