以下的问题由我斌哥提供解决方案 https://me.csdn.net/Duktig19 他的 个人站点.
文中内容由本人测试和整理
环境
文中使用的环境是
"name": "vue-admin-template",
"version": "3.8.0"
using npm@6.4.1
using node@v10.14.2
先看三张图,正常都是服务器返回session,然后浏览器每次发请求都会带上这个sessino
前景概要
axios在跨域时默认不携带cookie
controller注解@CrossOrigin的origins默认是是*
axios规定不能是*
必须和前端保持一致
所以需要手动配置一下
解决成功后如下图,服务器返回的session每次客户端请求会带上
正题
报错
Failed to load http://localhost:9001/eduuser/login: Response to preflight request doesn't pass access control check: 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'. Origin 'http://localhost:9528' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
未能加载http://localhost:9001/eduuser/login:对飞行前请求的响应未通过访问控制检查:当请求的凭据模式为“包含”时,响应中的“访问控制-允许-起源”报头的值不能是通配符“*”。因此不允许访问源'http://localhost:9528'。XMLHttpRequest发起的请求的凭据模式由withCredentials属性控制。
步骤一
看在那里导入axios
在哪导入,配置就写在哪
这个项目好像不是在main.js导入axios
我这个项目是在utils下request.js
写在创建axios实例之前
axios.defaults.withCredentials = true;//Cookie跨域
注意:
eslint
是语法问题
把注释和分号去了就没了
编译过了就没事。
步骤2
此时如果没有编写后端返回指定响应头
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: * #这里不能为返回*
前端不接受 ,这就是上面一开始的报错
在对应请求接口的控制器上@CrossOrigin设置属性origins和allowCredentials
修改好控制器后,在访问该接口响应头中
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:9528 就不为*
成功,不会报错
步骤3
如果每个controller都要设置太累了
可以搞一个配置类
创建一个配置类
实现WebMvcConfigurer接口
重写addCorsMappings方法
在里面可以配置
package com.domoyun.eduservice.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class aconfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://localhost"+":9528")
.allowCredentials(true);
}
}