跨域问题

预期结果:

  • Option请求能够快速处理,不经过拦截器,直接返回结果
  • 其他请求如果不符合跨域规则,直接返回结果

解决方案:

spring中提供了CorsFilter类,已经为我们写好了跨域处理逻辑,只需要进行对应的跨域配置即可,推荐使用

@Configuration
public class CorsConfig {

    @Value("${service.corsOrigin}")
    private String corsOrigins;

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        for (String corsOrigin : corsOrigins.split(",")) {
            corsConfiguration.addAllowedOrigin(corsOrigin);
        }
        // "Origin, X-Requested-With, Content-Type, Accept"
        corsConfiguration.addAllowedHeader("*");
        // "POST, GET"
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setMaxAge(3600L);
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }

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

还有如下一种方法,该方法会在拦截器执行之后执行,不符合我的需求,不推荐使用

@Component
public class MvcConfig extends WebMvcConfigurationSupport {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")// 允许请求方法
                .maxAge(3600L)
                .allowedHeaders("*")// 允许头部设置
                .allowCredentials(true);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值