springboot项目可以通过添加配置的方式来处理跨域:

    1. @Configuration
    2. public class CorsConfig implements WebMvcConfigurer {
    3. @Override
    4. public void addCorsMappings(CorsRegistry registry) {
    5. registry.addMapping("/**")
    6. .allowCredentials(true)
    7. .allowedOriginPatterns("*")
    8. .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
    9. .maxAge(3600);
    10. }
    11. }

    如果是security项目的话,需要添加以下的额外配置:

    1. @EnableWebSecurity
    2. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    3. @Override
    4. protected void configure(HttpSecurity http) throws Exception {
    5. http
    6. // by default uses a Bean by the name of corsConfigurationSource
    7. .cors()
    8. ...
    9. }
    10. // 如果已经配置了上方针对SpringMVC的配置,则下方的配置可以省略
    11. @Bean
    12. CorsConfigurationSource corsConfigurationSource() {
    13. CorsConfiguration configuration = new CorsConfiguration();
    14. configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
    15. configuration.setAllowedMethods(Arrays.asList("GET","POST"));
    16. UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    17. source.registerCorsConfiguration("/**", configuration);
    18. return source;
    19. }
    20. }