目录
跨域常见的几种情况
- 域名不同,eg. www.baidu.com、www.mall.baidu.com,下级域名也算跨域
- 应用使用的端口不同,eg. 80、8080
- 使用的协议不同,eg. http、https
满足以上任意一个就算跨域。
后端解决跨域的方案很多,常见的如下。
后端springboot解决跨域问题
方式一 @CrossOrigin注解
在controller的映射方法上加@CrossOrigin(“*”),表示允许该方法映射的url允许跨域访问;也可以直接加在controller上,表示该controller中映射的所有url都允许跨域访问。
此种方式比较鸡肋,适合只允许极少数资源跨域访问的情况。
方式二 添加bean CorsFilter | CorsWebFilter
spring webmvc 是添加 CorsFilter,spring webflux 是添加 CorsWebFilter
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
config.setAllowCredentials(true);
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
//应用config的路径
configSource.registerCorsConfiguration("/**", config);
return new CorsFilter(configSource);
}
原理:生成跨域过滤器CorsFilter的实例,对请求进行预处理,允许跨域。
优点:可以按url精细控制跨域
方式三 实现WebMvcConfigurer | WebFluxConfigurer接口,重写addCorsMappings()
spring webmvc 是实现 WebMvcConfigurer接口,spring webflux 是实现 WebFluxConfigurer接口
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
/**
* 接口中此方法的权限为default,需要修改为public
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("*").allowedHeaders("*").allowedMethods("*").allowCredentials(true);
// registry.addMapping("/user/**").allowedHeaders("*").allowedMethods("*").allowCredentials(true);
// registry.addMapping("/order/**").allowedHeaders("*").allowedMethods("*").allowCredentials(true);
}
}
优点:可以按url精细控制跨域