springboot 跨域处理示例代码

springboot处理跨域请求代码

在前、后端开发分离场景下,前段通过接口获取后端的数据,不可避免的碰到CORS问题,这里主要讲述后端代码允许修改的方案,记录springboot处理跨域的代码示例。如果后端是第三方提供,一般处理方案有自己封装第三方接口和用nginx等反向代理服务,不在这里讲述。

拦截http的OPTIONS方法,不要传递到controller方法

public class MyFilter extends HandlerInterceptorAdapter {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
            if (request.getMethod().equals("OPTIONS")) {
                return true;
            }
            //认证或其他业务代码
            return true;
        }
    }

跨域http头设置代码如下:

 @Configuration
  public class CorsConfig {
     @Bean
     public FilterRegistrationBean corsFilter() {
         UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
         CorsConfiguration config = new CorsConfiguration();
         // 打开支持GET、POST、HEAD方法开关
         config.applyPermitDefaultValues();
         // true,接受浏览器cookie;false,不接受cookie
         config.setAllowCredentials(false);
         // 允许的域名
         config.setAllowedOrigins(Arrays.asList(allowedOrigin.split(",")));
         // 允许的额外消息头(默认:Cache-Control, Content-Language, Expires, Last-Modified, or Pragma. ),此处token为自定义头
         config.setAllowedHeaders(Arrays.asList("token", "Content-Type"));
          // 允许的方法
         config.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS"));
         // 客户端可以拿到的额外消息头(默认:Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma)
         config.setExposedHeaders(Arrays.asList("token", "content-disposition"));
         // Access-Control-Max-Age Header
         source.registerCorsConfiguration("/**", config);
         FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
         bean.setOrder(0);
         return bean;
  }
}

猜你喜欢

转载自blog.51cto.com/13166529/2175942
今日推荐