解决方案 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*'

以下的问题由我斌哥提供解决方案 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);
    }
}
  • 5
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值