SHO酱的Blog

SHO酱的Blog

Spring Boot 跨域请求配置

2018-11-16

配置

  • Java版本:1.8
  • Spring Boot 版本:2.1.0.RELEASE

代码

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 {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 1添加允许使用的域名,也可以用"*"表示任何域名
        corsConfiguration.addAllowedOrigin("http://localhost:63341");
        corsConfiguration.addAllowedOrigin("http://localhost:63342");
        // 2允许任何头
        corsConfiguration.addAllowedHeader("*");
        // 3允许任何方法(post、get等)
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 4
        return new CorsFilter(source);
    }
}

参考

springboot跨域配置