Springboot unified cross-domain configuration

Preface: What cross-domain yes?

To know the concept of cross-domain, let's be clear how the same domain:

The same domain refer to the same protocol, the same ip, the same port

If there is one Triples different cross-domain arises.

When the front end of the separation doing projects, the background ajax request through port, is inevitable cross-domain

E.g:

I start the front-end server node.js backend interface to access via html

The following cross-domain error failure occurs

CORS solve cross-domain problems

CORS is a W3C standard, stands for "Cross-Origin Resource Sharing" (Cross-origin resource sharing). It allows the browser to cross the source server, issued a request XMLHttpRequest, which overcomes the limitations of AJAX only homologous use.

Basically all current browsers implement the standard CORS, in fact, almost all browsers ajax requests are based on CORS mechanism, but may usually front-end developers do not care about it (so that in fact the main solution is now CORS consider the question of how to achieve the background)   

 We realize in java is write a filter to set the source, the head and allow cross-domain method

code show as below:

/ * * 
 * Cross-domain configuration 
 * / 
@Configuration 
public  class CorsConfig {
   // set permit cross source 
  Private  static String [] = originsVal new new String [] {
       " 127.0.0.1:8080 " ,
       " localhost: 8080 " ,
       " Google.com " 
  }; 

  / * * 
   * cross-domain filter 
   * 
   * @return 
   * / 
  @Bean 
  public corsFilter corsFilter () { 
    UrlBasedCorsConfigurationSource Source = new new UrlBasedCorsConfigurationSource();
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    this.addAllowedOrigins(corsConfiguration);
    corsConfiguration.addAllowedHeader("*");
    corsConfiguration.addAllowedMethod("*");
    corsConfiguration.addAllowedOrigin("*");
    source.registerCorsConfiguration("/**", corsConfiguration);
    return new CorsFilter(source);
  }

  private void addAllowedOrigins(CorsConfiguration corsConfiguration) {
    for (String origin : originsVal) {
      corsConfiguration.addAllowedOrigin("http://" + origin);
      corsConfiguration.addAllowedOrigin("https://" + origin);
    }
  }
}

 

After writing this category to restart the server configuration you can see the page display properly

appendix


 

Extended Information:

Guess you like

Origin www.cnblogs.com/wutongshu-master/p/10948366.html