最新Spring Boot 跨域配置,親測好用
阿新 • • 發佈:2022-05-25
背景:
-
網上有很多跨域配置,但都存在各種各樣問題;經過改良和測試後,最終形成一個穩定配置版本,我的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;
}
}