1、如果只是一個簡單的springboot demo,用以下設定就行
新建config類別
``` import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * @author yk * @date 2021/7/19 14:36 */ @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOriginPatterns("*") .allowedMethods("*") .maxAge(3600) .allowCredentials(true); } } ```
2、但是實際開發中我們需要結合,spring-security、oauth2等等,就會發現上面的配置失效了,那是因為前面的Filter優先權太高了,那我們可以採取如下配置
``` import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; /** * @author yk * @date 2021/7/19 16:21 */ @Configuration public class CrosConfig { @Bean public FilterRegistrationBean corsFilter() { CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOriginPattern("*"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); //这里设置优先级最高 bean.setOrder(Ordered.HIGHEST_PRECEDENCE); return bean; } }
以上是springboot2.4跨域配置問題怎麼解決的詳細內容。更多資訊請關注PHP中文網其他相關文章!