SpringBoot+VUE跨域问题

巧了我就是萌 提交于 2019-12-01 16:34:50

场景及问题描述:

项目为前后端分离,后端项目使用Maven多模块项目+SpringBoot,前端使用 VUE。

后端在登录接口保存当前用户信息到session,前端请求后端接口,后端拦截器无法从session中获取当前登录的用户,前端出现以下跨域报错

 

错误信息:

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.

 

问题分析:

转自:https://www.jianshu.com/p/c115e4a24977

当请求的凭据模式为include时,相应中的Access-Control-Allow-Origin标头的值不能是通配符 "*"

如在请求定义中设置withCredentials标志,则会在请求中传递cookie等。
如果服务器返回任何set-cookie响应头, 那么必须返回Access-Control-Allow-Credentials: true, 否则将不会在客户端上创建 cookie
如果你这样设置,你需要同时指定了确切的Access-Control-Allow-Origin响应头,因为Access-Control-Allow-Origin: 不具有凭证兼容

--->当请求中携带cookie时, Access-Control-Allow-Origin必须要有确切的指定, 不能是通配符(*), 而withCredentials是跨域安全策略的一个东西

 

解决方案:

1、前端vue设置全局参数withCredentials : true

2、后端相关Controller添加跨域注解@CrossOrigin

3、后端新建CorsConfig类,继承WebMvcConfigurerAdapter,并重写addCorsMappings方法

@Configuration
@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer {
 
    public void addCorsMappings(CorsRegistry registry) {
        //设置允许跨域的路径
        registry.addMapping("/**")
                //设置允许跨域请求的域名
                .allowedOrigins("*")
                //这里:是否允许证书 不再默认开启
                .allowCredentials(true)
                //设置允许的方法
                .allowedMethods("*")
                //跨域允许时间
                .maxAge(3600);
    }
    
}

 

相关问题博客:vuejs前后端分离,session问题

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!