1. 报错信息
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 发送前端请求, 后端配置了Access-Control-Allow-Origin 为 "*", 报错信息如上文
3. 原因分析
这个问题是关于CORS(跨源资源共享)策略的错误。当你使用XMLHttpRequest或Fetch API发送请求时,浏览器会检查一个特殊的HTTP头'Access-Control-Allow-Origin'。如果这个头的值是' ',而请求的credentials mode是'include',那么浏览器会抛出一个错误。这是因为浏览器为了安全起见,不允许在credentials mode为'include'的情况下使用通配符' '。
4. 解决方案
- 不发送credentials(例如cookies): 如果你不需要发送cookies或HTTP认证信息,你可以尝试在请求中不包含这些信息。你可以通过设置XMLHttpRequest的withCredentials属性或Fetch API的credentials属性为false来实现。在axios中,你可以这样做:
javascript复制代码
axios.defaults.withCredentials = false;
或者在单个请求中:
javascript复制代码
axios.get(url, { withCredentials: false })
注意这将阻止所有基于XMLHttpRequest或Fetch API的请求发送credentials。
- 更改服务器的CORS策略: 如果你需要对特定服务器发送credentials,你需要更改服务器的CORS策略。这需要服务器管理员的帮助,但一般来说,他们可以设置'Access-Control-Allow-Origin'头为你的请求域,而不是'*'。例如,如果你的请求是针对'example.com'的,那么他们可以将'Access-Control-Allow-Origin'设置为'your-react-app.com',而不是'*'。