问题描述:本来没问题来着,过了几天,突然不行了,报错如下
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);
}
}