Three methods of SpringBoot project to solve cross-domain (backend)

The cross-domain error message is as follows:

Access to XMLHttpRequest at 'http://localhost:8181/list' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Same Origin Policy

The protocol, domain name, and port are all the same, which means the same source

Vue (front end): http://localhost:8080

Spring Boot (backend): http://localhost:8181/list

CORS:Cross Origin Resource Sharing

Three solutions to cross domain in Spring Boot project

1. Add the @CrossOrigin annotation to the target method or class

@GetMapping("/list")
@CrossOrigin
public List<String> list(){
    List<String> list = Arrays.asList("Java","C++","Go");
    return list;
}

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("*");
    }
}

Guess you like

Origin blog.csdn.net/m0_64210833/article/details/128894243