Springboot統一跨域配置


前言:跨域是什么?

要知道跨域的概念,我們先明確怎樣算是同一個域:

同一個域指的是同一協議,同一ip,同一端口

如果這三同中有一者不同就產生了跨域。

在做前后端分離的項目中,通過ajax請求后台端口時,跨域是不可避免的

例如:

我啟動node.js前端服務通過html訪問后台接口

這里的端口不一致就會出現下面跨域失敗的錯誤

CORS解決跨域問題

CORS是一個W3C標准,全稱是"跨域資源共享"(Cross-origin resource sharing)。它允許瀏覽器向跨源服務器,發出XMLHttpRequest請求,從而克服了AJAX只能同源使用的限制。

基本上目前所有的瀏覽器都實現了CORS標准,其實目前幾乎所有的瀏覽器ajax請求都是基於CORS機制的,只不過可能平時前端開發人員並不關心而已(所以說其實現在CORS解決方案主要是考慮后台該如何實現的問題)   

 我們在java中的實現就是寫一個過濾器來設置允許跨域的源、頭部和方法

代碼如下:

/**
 * 跨域配置
 */
@Configuration
public class CorsConfig {
  // 設置允許跨域的源
  private static String[] originsVal = new String[]{
      "127.0.0.1:8080",
      "localhost:8080",
      "google.com"
  };

  /**
   * 跨域過濾器
   *
   * @return
   */
  @Bean
  public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    this.addAllowedOrigins(corsConfiguration);
    corsConfiguration.addAllowedHeader("*");
    corsConfiguration.addAllowedMethod("*");
    corsConfiguration.addAllowedOrigin("*");
    source.registerCorsConfiguration("/**", corsConfiguration);
    return new CorsFilter(source);
  }

  private void addAllowedOrigins(CorsConfiguration corsConfiguration) {
    for (String origin : originsVal) {
      corsConfiguration.addAllowedOrigin("http://" + origin);
      corsConfiguration.addAllowedOrigin("https://" + origin);
    }
  }
}

 

寫完這個配置類之后重啟服務器就可以看到頁面正常顯示了

附錄


 

擴展資料:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM