问题描述

在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.

解决方案

在springboot2.x版本以后,点开注解源码可以看到credentials默认是关闭的,该值是一个布尔值,表示是否允许发送 Cookie 。默认情况下, Cookie 不包括在 CORS 请求之中,设置为 true,即表示服务器明确许可, Cookie 可以包含中跨域请求中,一起发送给服务器。这个值也只能设置为 true ,如果服务器不要浏览器发送 Cookie,删除该字段即可。

在这里插入图片描述
因此,在注解之后,需要显示设置为开启

@CrossOrigin(originPatterns = "*",allowCredentials = "true")

注意到上面我还设置了一个参数 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);
    }
}



Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐