最新Spring Boot 跨域配置,親測好用

背景:

  • 網上有很多跨域配置,但都存在各種各樣問題;經過改良和測試後,最終形成一個穩定配置版本,我的Spring Boot版本是2.5.1

問題:

  • 前後端分離後,進行聯調,發現瀏覽器出報跨域問題

 

解決方案:

  • 在config配置文件中添加下面代碼類。這裏很重要的一點是,在有其他攔截器的時候,通過bean.setOrder(0);設置加載順序,我是通過這個方式解決問題的
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class GlobalCorsConfig {
   
    @Bean
    public FilterRegistrationBean corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOriginPattern("*");
        //是否允許發送Cookie信息
        config.setAllowCredentials(Boolean.TRUE);
        //開放哪些Http方法,允許跨域訪問
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("OPTIONS");
        //允許HTTP請求中的攜帶哪些Header信息
        config.addAllowedHeader("*");
        //暴露哪些頭部信息(因爲跨域訪問默認不能獲取全部頭部信息)
        //config.addExposedHeader("*");
        //添加映射路徑,“/**”表示對所有的路徑實行全局跨域訪問權限的設置
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);

        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(configSource));
   //設置爲第一 bean.setOrder(0); return bean; } }



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