spring cloud-前端跨域問題的解決方案


當我們需要將spring boot以restful接口的方式對外提供服務的時候,如果此時架構是前后端分離的,那么就會涉及到跨域的問題,那怎么來解決跨域的問題了,下面就來探討下這個問題。

解決方案一:在Controller上添加@CrossOrigin注解

使用方式如下:

 

  1.  
    @CrossOrigin // 注解方式
  2.  
    @RestController
  3.  
    public class HandlerScanController {
  4.  
     
  5.  
     
  6.  
    @CrossOrigin(allowCredentials="true", allowedHeaders="*", methods={RequestMethod.GET,
  7.  
    RequestMethod.POST, RequestMethod.DELETE, RequestMethod.OPTIONS,
  8.  
    RequestMethod.HEAD, RequestMethod.PUT, RequestMethod.PATCH}, origins= "*")
  9.  
    @PostMapping("/confirm")
  10.  
    public Response handler(@RequestBody Request json){
  11.  
     
  12.  
    return null;
  13.  
    }
}

 

解決方案二:全局配置

代碼如下:

 

  1.  
    @Configuration
  2.  
    public class MyConfiguration {
  3.  
     
  4.  
    @Bean
  5.  
    public WebMvcConfigurer corsConfigurer() {
  6.  
    return new WebMvcConfigurerAdapter() {
  7.  
    @Override
  8.  
    public void addCorsMappings(CorsRegistry registry) {
  9.  
    registry.addMapping( "/**")
  10.  
    .allowCredentials( true)
  11.  
    .allowedMethods( "GET");
  12.  
    }
  13.  
    };
  14.  
    }
  15.  
    }

解決方案三:結合Filter使用
在spring boot的主類中,增加一個CorsFilter

 

  1.  
    /**
  2.  
         *
  3.  
         * attention:簡單跨域就是GET,HEAD和POST請求,但是POST請求的"Content-Type"只能是application/x-www-form-urlencoded, multipart/form-data 或 text/plain
  4.  
         * 反之,就是非簡單跨域,此跨域有一個預檢機制,說直白點,就是會發兩次請求,一次OPTIONS請求,一次真正的請求
  5.  
         */
  6.  
         @Bean
  7.  
         public CorsFilter corsFilter() {
  8.  
            final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  9.  
            final CorsConfiguration config = new CorsConfiguration();
  10.  
            config.setAllowCredentials( true); // 允許cookies跨域
  11.  
            config.addAllowedOrigin( "*");// #允許向該服務器提交請求的URI,*表示全部允許,在SpringMVC中,如果設成*,會自動轉成當前請求頭中的Origin
  12.  
            config.addAllowedHeader( "*");// #允許訪問的頭信息,*表示全部
  13.  
            config.setMaxAge( 18000L);// 預檢請求的緩存時間(秒),即在這個時間段里,對於相同的跨域請求不會再預檢了
  14.  
            config.addAllowedMethod( "OPTIONS");// 允許提交請求的方法,*表示全部允許
  15.  
            config.addAllowedMethod( "HEAD");
  16.  
            config.addAllowedMethod( "GET");// 允許Get的請求方法
  17.  
            config.addAllowedMethod( "PUT");
  18.  
            config.addAllowedMethod( "POST");
  19.  
            config.addAllowedMethod( "DELETE");
  20.  
            config.addAllowedMethod( "PATCH");
  21.  
            source.registerCorsConfiguration( "/**", config);
  22.  
            return new CorsFilter(source);
  23.  
        }
當然,如果微服務多的話,需要在每個服務的主類上都加上這么段代碼,這違反了D


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM