springBoot跨域請求與配置

關於跨域問題 就不多介紹了!

針對跨域問題的解決方式:

  • CORS (Cross-Origin Resource Sharing)跨來源資源共享
  • JSONP

 

CORS 對比 JSONP

都能解決 Ajax直接請求普通文件存在跨域無權限訪問的問題

  1. JSONP只能實現GET請求,而CORS支持所有類型的HTTP請求
  2. 使用CORS,開發者可以使用普通的XMLHttpRequest發起請求和獲得數據,比起JSONP有更好的錯誤處理
  3. JSONP主要被老的瀏覽器支持,它們往往不支持CORS,而絕大多數現代瀏覽器都已經支持了CORS

這裏使用CORS最簡單的一種

@Bean
	public FilterRegistrationBean registFilter() {
		FilterRegistrationBean registration = new FilterRegistrationBean();
		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 {
		String allowOrigin = request.getHeader("Origin");
		String allowMethods = "GET,PUT, POST, DELETE";
		String allowHeaders = "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
				
				chain.doFilter(request, response);
			}

			public void destroy() {
				// TODO Auto-generated method stub
				log.info("過濾器destroy!");
			}
		});
		return registration;
	}

 

二: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,目前也就兩個可以用

這兩個也都大同小異,因爲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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章