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.

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));
}
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
SpringCloud Webflux过滤器增加header传递方式
这篇文章主要介绍了SpringCloud Webflux过滤器增加header传递方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2023-02-02
SpringBoot集成WebServlet出现自定义servlet请求失败的问题解决方案
SpringBoot中以Bean方式注册Servlet时遇到的问题,通过了解DispatcherServlet的原理,发现默认路径冲突是主要原因,本文介绍SpringBoot集成WebServlet出现自定义servlet请求失败的问题解决方案,感兴趣的朋友一起看看吧2025-03-03
Java面试题篇之Sleep()方法与Wait()方法的区别详解
这篇文章主要给大家介绍了关于Java面试题篇之Sleep()方法与Wait()方法区别的相关资料,wait()是Object类中的方法,而sleep()是Thread类中的静态方法,wait()方法用于多个线程之间的协作和通信,而sleep()方法用于线程的休眠,需要的朋友可以参考下2024-07-07
Mybatis-Plus使用saveOrUpdate及问题解决方法
本文主要介绍了Mybatis-Plus使用saveOrUpdate及问题解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2023-01-01


最新评论