java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot跨域配置不生效

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

作者:wztcoder

前端请求时遇到“Access to XMLHttpRequest has been blocked by CORS policy”报错?本文深入浅出地讲解Spring Boot中3种跨域配置方法,包括@CrossOrigin注解、全局CorsFilter和WebMvcConfigurer,帮你快速解决跨域问题,提升开发效率

允许跨域的配置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.

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;

@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

两种实现形式:单域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));

    }

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文