每日总结2023年11月17日

Access to XMLHttpRequest at 'http://localhost:8090/user/list' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

这是今天做SpringBoot+Vue项目时候遇到的问题,查了一下这是SpringBoot的跨域问题,这边给大家推荐文章链接【精选】SpringBoot解决跨域的5种方式_springboot 跨域-CSDN博客

我这边采用的是重写WebMvcConfigurer(全局跨域)方法,代码如下

@Configuration
public class CorsConfig implements WebMvcConfigurer {
 
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                //是否发送Cookie
                .allowCredentials(true)
                //放行哪些原始域
                .allowedOrigins("*")
                .allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"})
                .allowedHeaders("*")
                .exposedHeaders("*");
    }
}

但是采用这种方法以后后续还有一个问题就是会报一个错误

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时,allowedOrigins不能包含特殊值"*",因为它不能在"Access-Control-Allow-Origin"响应头中设置。 要允许凭证指向一组起源,可以显式地列出它们,或者考虑使用“allowedOriginPatterns”代替。原文链接:【解决】When allowCredentials is true, allowedOrigins cannot contain the special value “*“ since-CSDN博客

所以解决方式就是把allowedOrigins改成allowedOriginPatterns,最后不再报错问题解决

posted @ 2023-11-17 13:39  那啥cjj  阅读(9)  评论(0编辑  收藏  举报