填坑 The value of the ‘Access-Control-Allow-Origin‘ header in the response must not be the wildcard ‘*

问题描述:本来没问题来着,过了几天,突然不行了,报错如下

1.报错

Access to XMLHttpRequest at 'http://localhost:8443/api/register' from origin 'http://localhost:8080' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

2.概要

axios在跨域时默认不携带cookie

controller注解@CrossOrigin的origins默认是是*

axios规定不能是*

必须和前端保持一致

所以需要手动配置一下

解决成功后如下图,服务器返回的session每次客户端请求会带上
在这里插入图片描述

 

2.解决步骤

 1.前端 找到导入axios的地方,我的是在main.js里面,加上(写在创建axios实例之前)

axios.defaults.withCredentials = true// Cookie跨域

2.后端找到对应接口

此时如果没有编写后端返回指定响应头
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: * #这里不能为返回*
前端不接受 ,这就是上面一开始的报错
在对应请求接口的控制器上@CrossOrigin设置属性origins和allowCredentials

origins属性可以不设置

再次测试发现成功了,整理了一下前辈的经验,再结合自己的修改,解决了bug,真的感动哭了,写了一整个下午,查对应教程都解决不了。

给各位一个参考,愿君路上无bug

 

补充:后面又遇到了。如果上面还是不行,试试以下方案,可以在springboot后端配置一个config实现全局跨域

springboot的话,如果没有config层的话,建议做一个,然后在里面编写一个java文件,参考如下,实现全局跨域.

@SpringBootConfiguration
public class MyWebConfigurer implements WebMvcConfigurer {

@Override
    public void addCorsMappings(CorsRegistry corsRegistry){
        /**
         * 所有请求都允许跨域,使用这种配置就不需要
         * 在interceptor中配置header了
         */
        corsRegistry.addMapping("/**")
                .allowCredentials(true)
                .allowedOrigins("http://localhost:8080")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .allowedHeaders("*")
                .maxAge(3600);
    }

}

 

 

 

 

 

 

 

 

 

 

 

 

  • 10
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值