springboot彻底实现跨域方案

前言

因目前采用前后端分离的写法,当部署了服务器之后,前端web端调用服务器就会产生跨域的问题。

解决方案

springboot官方给出的解决方案为:

@Configuration
public class MyConfiguration {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**")
                	.allowedOrigins("*")
                	.allowedMethods("*")
                	.allowCredentials(true);
            }
        };
    }
}

如果想单独对某个接口做跨域可使用@CrossOrigin注解

注意

上述方式可以达到跨域的效果,但是由于springboot采用的方式为在调用DispatchServlet接口时进行interceptor拦截,而crosinterceptor是放在最后一层,故如果说各位自己写的代码中增加了interceptor,并且在OPTIONS的方法执行的时候被前面的某一层拦截下来了,那么就会跨域失败。

  • 此时可采用过滤器
private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
    }

    /* *
     * 跨域过滤器
     *
     * @return
     * */
    @Bean
    public CorsFilter corsFilter() {
       UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
  • 也可以在自己的interceptor中剔除OPTIONS方法的拦截
@Component
public class LoginCheckInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (CorsUtils.isPreFlightRequest(request)) {
            return true;
        }
        // 拦截处理逻辑
        ...
    }
}

这样就能达到彻底实现跨域的做法了。

小结

  1. 如果自己的项目中没有增加interceptor,可尽情使用springboot提供的跨域方式
  2. 如果自己的项目中增加了interceptor,可增加corsfilter进行过滤
  3. 如果自己的项目中增加了interceptor,又不想增加filter,那么可将OPTIONS方法从自己的拦截器中剔除
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值