允许跨域的配置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));
}
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论