首页 > 其他分享 >解决springboot添加@CrossOrigin支持跨域不起作用

解决springboot添加@CrossOrigin支持跨域不起作用

时间:2022-10-18 19:58:28浏览次数:50  
标签:springboot springframework 跨域 org import config CrossOrigin

问题描述
在springboot开发中,为解决跨域请求问题,在代码中添加注解@CrossOrigin不起任何作用。


后端报错信息如下

java.lang.IllegalArgumentException: When allowCredentials is true,
allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header.
To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.
1
2
3
解决方案
在springboot2.x版本以后,点开注解源码可以看到credentials默认是关闭的,该值是一个布尔值,表示是否允许发送 Cookie 。默认情况下, Cookie 不包括在 CORS 请求之中,设置为 true,即表示服务器明确许可, Cookie 可以包含中跨域请求中,一起发送给服务器。这个值也只能设置为 true ,如果服务器不要浏览器发送 Cookie,删除该字段即可。


因此,在注解之后,需要显示设置为开启

@CrossOrigin(originPatterns = "*",allowCredentials = "true")
1
注意到上面我还设置了一个参数 originPatterns,在1.x版本的springboot中,是以origins作为参数,而新版本则改为了originPatterns,但是默认还是使用的origins,上面的报错也在提醒我们用originPatterns这个参数代替。


综上,跨域问题得以解决。

方案二
以上注解只能解决局部跨域,也就是每一个controller都要加注解。要想一劳永逸可以编写配置类。值得注意的是我上面提到高版本的springboot参数换成了originPatterns。而我看很多的博客都写的类似如下老版本的origins,照着配置仍然解决不了问题。


正确的写法应该是下面这样


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CORSConfig {
/**
* 允许跨域调用的过滤器
*/
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
//允许白名单域名进行跨域调用
config.addAllowedOriginPattern("*");
//允许跨越发送cookie
config.setAllowCredentials(true);
//放行全部原始头信息
config.addAllowedHeader("*");
//允许所有请求方法跨域调用
config.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}

 

————————————————
版权声明:本文为CSDN博主「BigFreezer」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_45721173/article/details/124634565

标签:springboot,springframework,跨域,org,import,config,CrossOrigin
From: https://www.cnblogs.com/wxzai/p/16803844.html

相关文章