SpringBoot跨域配置不生效怎么办?3种解决方法详细说明

作者:袖梨 2026-08-05

处理SpringBoot跨域配置不生效怎么办?3种解决方法详细说明这类问题时,先确认目标场景,再按步骤核对配置或玩法细节。

允许跨域的配置3种解决办法

错误示例:

:8081/?role=[2]&id=653#/:1 Access to XMLHttpRequest at 'http://172.17.10.200:8086/bigdatatools/bigdata/zhanhang/ALLTblPositionTypeInfo' from origin 'http://172.17.10.200:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

SpringBoot跨域配置不生效怎么办?3种解决方法详解

1.在Controller层添加@CrossOrigin注解

2.在全局配置文件中添加跨域配置

3.创建一个配置类实现WebMvcConfigurer接口,在其中添加跨域配置

在Spring Boot的application.yml文件中设置跨域允许可以通过配置 CorsFilter 或使用 WebMvcConfigurer 来实现。或者在方法上增加允许的注解@CrossOrigin

方法一:使用 CorsFilter

在application.yml中增加以下配置:

在某种情况下可能会不生效喔。方法二稳一点,方法三临时测试很好用。

spring:  filter:    cors:      enabled: true      url-pattern: /*      allowed-origins: "http://localhost:8081, http://172.16.10.200:8081, http://172.16.10.201:8081"      allowed-methods: GET,POST,PUT,DELETE,OPTIONS      allowed-headers: "*"      allow-credentials: true      max-age: 3600

方法二:使用 WebMvcConfigurer

创建一个配置类实现 WebMvcConfigurer 接口,覆盖 addCorsMappings 方法:

import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.CorsRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configurationpublic class CorsConfig implements WebMvcConfigurer {    @Override    public void addCorsMappings(CorsRegistry registry) {        // 设置允许跨域的路径        registry.addMapping("/**")                // 设置允许跨域请求的域名            .allowedOrigins("http://localhost:8081", "http://172.16.10.200:8081", "http://172.16.10.201:8081")                // 设置允许的请求方式            .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")                // 设置允许的header属性            .allowedHeaders("*")                // 是否允许cookie            .allowCredentials(true)                // 设置允许跨域的时长            .maxAge(3600);    }}

方法三:在controller层的方法上增加允许跨域的注解@CrossOrigin

两种实现形式:单域ip 多域ip

1.单域

@CrossOrigin(origins = "http://localhost:8081") //允许跨域

2.多域

@CrossOrigin(origins = {"http://localhost:8081","http://172.17.10.200:8081","http://172.17.10.201:8081"}) //允许跨域

例:多域示例

@CrossOrigin(origins = {"http://localhost:8081","http://172.17.10.200:8081","http://172.17.10.201:8081"}) //允许跨域    @GetMapping(value = "/getALLEnterprisePositionForZh")    public Object getALLTblPositionInfo(@Param("positionTypeId") Integer positionTypeId) {        log.info("positionTypeId:{}", positionTypeId);        return BaseResponse.ok(bigDataAnalysisService.getALLEnterprisePositionForZh(positionTypeId));    }

总结

相关文章

精彩推荐