springboot全局跨域

兩種方式任意一種即可
1.在config裡面添加Cros文件

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
@Order(1)
public class Cross {

/**
 * 跨域解決
 * @return
 */
@Bean
public CorsFilter doFilter() {
	//1.添加CORS配置信息
	CorsConfiguration config = new CorsConfiguration();
	//放行哪些原始域
	config.addAllowedOrigin("*");
	//放行哪些原始域(请求方式)
    config.addAllowedMethod("*");
    //放行哪些原始域(头部信息)
    config.addAllowedHeader("*");
    //2.添加映射路径
    UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
    configSource.registerCorsConfiguration("/**", config);

    //3.返回新的CorsFilter.
    return new CorsFilter(configSource);
}

}
2.在運行的Application裡面添加代碼
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin(""); // 1 设置访问源地址
corsConfiguration.addAllowedHeader("
"); // 2 设置访问源请求头
corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
return corsConfiguration;
}

@Bean
public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", buildConfig()); // 4 对接口配置跨域设置
    return new CorsFilter(source);
}

你可能感兴趣的:(後端跨域)