跨域注解CrossOrigin的坑

  • Post author:
  • Post category:其他




跨域注解CrossOrigin

记录踩过的坑


首先这是我springboot的版本号,应该是springboot版本的问题,这个注解里的很多参数已经被弃用了

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

@CrossOrigin注解是用来完成跨域请求的。

之前CrossOrigin注解的origins是默认为*的,这次项目里我也只写了个*,然后allowCredentials参数写为了true, 表示session也是可以支持跨域请求的,多次请求都是用一个session。 然后项目就报错了。

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is 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.

他说allowCredentials为true的时候origins不能为*。这里也很简单,他不让用我们就配一个域名呗

@CrossOrigin(origins = "http://localhost:8000", allowedHeaders = "*", methods = {}, allowCredentials = "true")

表示同意来自我配的域名的请求,完美!



版权声明:本文为weixin_45870082原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。