跨域訪問(wèn)是什么,百度一下你就知道。
什么情況下能確定遇到跨域問(wèn)題了呢?
是使用js向服務(wù)起發(fā)送的請(qǐng)求
沒(méi)有返回結(jié)果,F(xiàn)12后發(fā)現(xiàn)錯(cuò)誤信息包含這個(gè):
XMLHttpRequest cannot load http://……. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://……' is therefore not allowed access.
服務(wù)器控制臺(tái),發(fā)送的請(qǐng)求是get或者post,但顯示的是options。為什么變了呢?通過(guò)OPTIONS請(qǐng)求握手一次的方式實(shí)現(xiàn)跨根域發(fā)送請(qǐng)求,就是先用它了試試能請(qǐng)求不。
因?yàn)閼校恢毕胝易詈?jiǎn)單的辦法,所以簡(jiǎn)單可行的主要有以下三個(gè)方法:
- 給響應(yīng)添加
response.setHeader('Access-Control-Allow-Origin:*');
,這個(gè)最簡(jiǎn)單了。但是在公司的eclipse封裝后的平臺(tái)上,我們沒(méi)找到這個(gè)應(yīng)該放在哪里………… - Spring MVC 從4.2版本開(kāi)始增加了對(duì)CORS的支持,可以使用@CrossOrigin注解進(jìn)行細(xì)粒度的配置。同理,不知道用在哪里……
- Tomcat下的配置,這個(gè)相比上兩個(gè)要單獨(dú)下載jar文件,但是更容易操作了。
下載cors-filter-1.7.jar,Java-property-utils-1.9.jar這兩個(gè)庫(kù)文件,放到lib目錄下。(可在http://search.maven.org上查詢并下載。)工程項(xiàng)目中web.xml中的配置如下:
<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>