当前位置: 代码网 > it编程>编程语言>Java > SpringBoot跨域配置不生效怎么办?3种解决方法详解

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

2026年08月04日 Java 我要评论
允许跨域的配置3种解决办法错误示例::8081/?role=[2]&id=653#/:1 access to xmlhttprequest at 'http://172.17.10.2

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

    }

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com