SpringBoot项目解决跨域的三种方法(后端)

跨域报错信息如下:

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.

同源策略

协议、域名、端口 3 个都相同就是同源

Vue(前端):http://localhost:8080

Spring Boot(后端):http://localhost:8181/list

CORS:Cross Origin Resource Sharing

Spring Boot 项目中解决跨域的 3 种方案

1、在目标方法上或者类上添加 @CrossOrigin 注解

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

2、添加 CORS 过滤器

@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、实现 WebMvcConfigurer 接口,重写 addCorsMappings 方法

扫描二维码关注公众号,回复: 14784273 查看本文章
@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("*");
    }
}

猜你喜欢

转载自blog.csdn.net/m0_64210833/article/details/128894243