Access-Control-Allow-Origin 设置后还是跨域报错?
我在本地开发时请求后端接口,明明在响应头里加了 Access-Control-Allow-Origin: *,但浏览器还是报跨域错误,这是为啥?
后端是用 Node.js 写的,我试过在 Express 里加中间件设置 CORS 头,也试过 Nginx 配置,但前端 fetch 请求依然被拦。控制台提示:「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’.」
我的前端代码是这样发请求的:
fetch('http://localhost:3001/api/data', {
method: 'GET',
credentials: 'include'
})
.then(res => res.json())
.then(data => console.log(data));
credentials: 'include'和Access-Control-Allow-Origin: *冲突了。当你需要发送凭据(比如cookies)时,浏览器安全策略不允许用通配符 * 来允许跨域。两种解决方案:
1. 如果你确实需要发送凭据,把通配符改成具体的origin:
2. 如果不需要发送凭据,前端去掉credentials选项:
第一种方案效率更高,因为避免了不必要的凭据传输。但记得要在Nginx里也同步修改配置,别只改Node.js那边。
credentials: 'include'就不能用通配符*了,改成具体域名就行:就这样