Spring boot 总结之跨域处理cors的方法
背景
现在做的很多项目都是前后端分离的,这就引出一个很常见的问题,我们的页面和接口是在不同域名下的,当我们通过ajax访问后端接口的时候就会出现跨域问题,这种问题我们怎么解决呢?一般来说就是cors和jsonp这两种方案。Spring简化了cors的配置,接下来我们来看一下它提供的cors。
跨域问题描述
Web开发经常会遇到跨域问题,解决方案有:jsonp,iframe,CORS等等。
CORS与JSONP相比:
1、JSONP只能实现GET请求,而CORS支持所有类型的HTTP请求。
2、使用CORS,开发者可以使用普通的XMLHttpRequest发起请求和获得数据,比起JSONP有更好的错误处理。
3、JSONP主要被老的浏览器支持,它们往往不支持CORS,而绝大多数现代浏览器都已经支持了CORS。
WebMvcConfigurer对象
我们可以初始化一个WebMvcConfigurer对象来配置我们的cors映射。
@Configuration
publicclassCorsCongiguration{
@Bean
publicWebMvcConfigurercorsConfigurer(){
returnnewWebMvcConfigurerAdapter(){
@Override
publicvoidaddCorsMappings(CorsRegistryregistry){
registry.addMapping("/api/**");//允许所有第三方域名访问该接口
//.allowedOrigins("http://domain2.com")//指定来源域名
//.allowedMethods("PUT","DELETE")
//.allowedHeaders("header1","header2","header3")
//.exposedHeaders("header1","header2")
//.allowCredentials(false).maxAge(3600);
}
};
}
}
继承WebMvcConfigurerAdapter
这种方式跟上面的方式很类似
@Configuration
@EnableWebMvc
publicclassCorsConfiguration_2extendsWebMvcConfigurerAdapter{
@Override
publicvoidaddCorsMappings(CorsRegistryregistry){
registry.addMapping("/api/**");
}
}
corsFilter
这种方式现在很少用
@Component
@EnableWebMvc
publicclassCorsFilterCongigurationextendsCorsFilter{
publicCorsFilterCongiguration(CorsConfigurationSourceconfigSource){
super(configSource);
}
@Bean
publicFilterRegistrationBeancorsFilter(){
UrlBasedCorsConfigurationSourcesource=newUrlBasedCorsConfigurationSource();
CorsConfigurationconfig=newCorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
//config.addAllowedOrigin("http://domain1.com");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/api/**",config);
FilterRegistrationBeanbean=newFilterRegistrationBean(newCorsFilter(source));
bean.setOrder(0);//必须在所有Filter之前
returnbean;
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。