關於跨域問題 就不多介紹了!
針對跨域問題的解決方式(這裏就簡單說一下第一種):
- CORS (Cross-Origin Resource Sharing)跨來源資源共享
- JSONP
- 代理請求方式
CORS請求原理
CORS是一個W3C標準,全稱是"跨域資源共享"(Cross-origin resource sharing)。它允許瀏覽器向跨源服務器,發出XMLHttpRequest請求,從而克服了AJAX只能同源使用的限制。
基本上目前所有的瀏覽器都實現了CORS標準,其實目前幾乎所有的瀏覽器ajax請求都是基於CORS機制的,只不過可能平時前端開發人員並不關心而已(所以說其實現在CORS解決方案主要是考慮後臺該如何實現的問題)。
CORS 對比 JSONP
都能解決 Ajax直接請求普通文件存在跨域無權限訪問的問題
- JSONP只能實現GET請求,而CORS支持所有類型的HTTP請求
- 使用CORS,開發者可以使用普通的XMLHttpRequest發起請求和獲得數據,比起JSONP有更好的錯誤處理
- JSONP主要被老的瀏覽器支持,它們往往不支持CORS,而絕大多數現代瀏覽器都已經支持了CORS
這裏使用CORS最簡單的一種
@Bean
public FilterRegistrationBean<Filter> registFilter() {
FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<Filter>();
registration.setFilter(new Filter() {
public void init(FilterConfig filterConfig) throws ServletException {
log.info("過濾器init!");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
allowCrossAccess((HttpServletRequest)request, (HttpServletResponse)response);
// 判斷是否是預請求 OPTIONS 是則放行
if((boolean) ((HttpServletRequest) request).getMethod().equals("OPTIONS")){
System.out.println(((HttpServletRequest) request).getMethod());
((HttpServletResponse) response).setStatus(HttpStatus.OK.value());
return;
}
chain.doFilter(request, response);
}
public void destroy() {
// TODO Auto-generated method stub
log.info("過濾器destroy!");
}
});
return registration;
}
protected void allowCrossAccess(HttpServletRequest request,HttpServletResponse response) {
String allowOrigin = "*";
// String allowOrigin = request.getHeader("Origin");
String allowMethods = "GET,PUT,OPTIONS,POST,DELETE";
String allowHeaders = "authorization,Origin,No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified,Cache-Control, Expires, Content-Type, X-E4M-With";
response.addHeader("Access-Control-Allow-Credentials", "true");
response.addHeader("Access-Control-Allow-Headers", allowHeaders);
response.addHeader("Access-Control-Allow-Methods", allowMethods);
response.addHeader("Access-Control-Allow-Origin", allowOrigin);
response.addHeader("Access-Control-Max-Age", "1800");//30 min
}
二:Nginx 配置支持Ajax跨域
這裏是一個nginx啓用COSR的參考配置:來源
#
# Wide-open CORS config for nginx
#
location / {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
#
# Custom headers and headers various browsers *should* be OK with but aren't
#
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
#
# Tell client that this pre-flight info is valid for 20 days
#
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
}
三:支持多域名配置的CORS Filter
因爲知道已經有可以用的庫可以解決,所以就沒重複造輪子了。其實因爲懶,看看別人的源碼算了。。。
在mvnrepository搜索cors-filter,目前也就兩個可以用
- org.ebaysf.web 的 cors-filter,項目地址:https://github.com/ebay/cors-filter
- com.thetransactioncompany的 cors-filter,項目地址:http://software.dzhuvinov.com/cors-filter.html
這兩個也都大同小異,因爲ebay開源在github上,也有詳細的README,那麼就以ebay的cors-filter爲例
配置
添加依賴包到項目:
<dependency>
<groupId>org.ebaysf.web</groupId>
<artifactId>cors-filter</artifactId>
<version>1.0.1</version>
</dependency>
添加配置(具體配置項,還是見項目的README.md吧)
<filter>
<filter-name>CORS Filter</filter-name>
<filter-class>org.ebaysf.web.cors.CORSFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value>http://192.168.56.129,http://192.168.56.130</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</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CORS Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
後面的第二、第三 轉自 http://www.cnblogs.com/sloong/p/cors.html
本文發佈後,無意看到一篇文章,這裏貼一下整理的相關跨域問題,比較詳細(推薦)
https://segmentfault.com/a/1190000012469713?utm_source=tag-newest