问题大集04-浏览器阻止从 本地 发起的跨域请求,因为服务器的响应头 Access-Control-Allow-Origin 设置为通配符 *
1、问题
localhost/:1 Access to XMLHttpRequest at 'xxx'(请求) from origin 'http://localhost:xxx'(本地) 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
并且请求已经发送成功(net::ERR_FAILED 200 (OK))
2、解决方法(仅针对axios和使用axios封装)
在请求的时候,如果不需要发送凭据(如 cookies 或 HTTP 认证信息),可以在请求中禁用 withCredentials
即在请求的时候,如果是get请求,在第二个参数的位置添加 { withCredentials: false // 禁用凭据
}
axios.get('xxx', { withCredentials: false // 禁用凭据})
.then(res=> console.log(res.data))
.catch(error => console.error('Error:', error));