Springboot中配置CORS解决前后端分离跨域问题

Springboot中配置CORS解决前后端分离跨域问题_第1张图片
image.png

Spring Boot:

/**
 * @ClassName: CorsConfig
 * @Description: 解决前后端分离调用时跨域问题.注意安全风险,更细粒度的控制,可在方法上 @CrossOrigin(origins = "url")
 * @author lengyu
 * @date 2017年7月22日 下午2:52:59
 * 
 */
@Configuration
public class CorsConfig {
    @Autowired
    private VhscProperties vhscProperties;

    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin(vhscProperties.getAllowedOrigins());
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }

}

前端Ajax:


你可能感兴趣的:(Springboot中配置CORS解决前后端分离跨域问题)