记录一个springboot 设置跨域 失效的问题

问题

前端请求springboot的接口报跨域,后端有接收到请求也能成功处理并返回结果,但前端无法接收结果。
后端通过继承WebMvcConfigurer有以下代码设置跨域:

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }

奇怪的是,另外一个项目也是这样设置的,可以成功跨域。

解决

百度后,有说是拦截配置执行的顺序的问题?(具体原因没想明白)使用推荐的方案,使用Filter来处理跨域,成功解决!

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
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 CorsConfig {
	
	@Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        // 使用setAllowedOrigin会出现IllegalArgumentException
        config.addAllowedOriginPattern("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }
}

posted @ 2022-11-28 14:54  流失的痕迹  阅读(426)  评论(0编辑  收藏  举报