What is cross domain?
Cross-domain means that the browser cannot execute scripts from other websites. It is caused by the browser's same-origin policy, a security restriction imposed by the browser.
The so-called homology means that the domain name, protocol, and port are the same, as long as there is one difference, it is cross-domain
3 solutions to cross-domain solutions in Spring Boot projects
1. @CrossOrigin annotation
Add the @CrossOrigin annotation to the controller class
@CrossOrigin
public class GoodsController {
}
2. Add CORS filter
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter(){
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(source);
}
}
3. Implement the WebMvcConfigurer interface and rewrite the addCorsMappings method
@Configuration
public class CorsConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods("GET","POST","PUT","DELETE","HEAD","OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}