商城首页欢迎来到中国正版软件门户

您的位置:首页 >SpringBoot跨域配置不生效怎么办?3种解决方法详解

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

  发布于2026-08-05 阅读(0)

扫一扫,手机访问

允许跨域的配置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种解决方法详解

其实,解决跨域问题无非三种思路:要么在Controller层加注解,要么在全局配置里做文章,要么专门创建一个配置类。下面把这三种方法拆开细说。

Spring Boot 中,跨域配置可以通过 CorsFilterWebMvcConfigurer 或者在方法上加 @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;

@Configuration
public 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 注解

这种方式支持单域和多域两种写法:

单域:

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

多域:

@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));

    }

总结

以上三种方法覆盖了日常开发中绝大多数的跨域需求。方法一配置简单但偶有失效,方法二稳重型项目首选,方法三适合临时测试或小范围开放。根据实际场景灵活选用就好。

本文转载于:https://www.jb51.net/program/368623ca8.htm 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注