Access-Control-Allow-Origin 设置后还是跨域报错?

码农铭轩 阅读 6

我在本地开发时请求后端接口,明明在响应头里加了 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));
我来解答 赞 2 收藏
二维码
手机扫码查看
2 条解答
UI利娜
UI利娜 Lv1
问题出在你的 credentials: 'include'Access-Control-Allow-Origin: * 冲突了。当你需要发送凭据(比如cookies)时,浏览器安全策略不允许用通配符 * 来允许跨域。

两种解决方案:

1. 如果你确实需要发送凭据,把通配符改成具体的origin:
// Express中间件
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', 'http://你的前端地址:端口');
res.header('Access-Control-Allow-Credentials', 'true');
next();
});


2. 如果不需要发送凭据,前端去掉credentials选项:
fetch('http://localhost:3001/api/data', {
method: 'GET'
// 去掉 credentials: 'include'
})


第一种方案效率更高,因为避免了不必要的凭据传输。但记得要在Nginx里也同步修改配置,别只改Node.js那边。
点赞
2026-03-05 18:05
♫林莹
♫林莹 Lv1
你用了 credentials: 'include' 就不能用通配符 * 了,改成具体域名就行:

app.use(cors({
origin: 'http://localhost:3000',
credentials: true
}));


就这样
点赞
2026-03-05 05:00