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;
  }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章