node.js - CORS 错误:“响应中的 'Access-Control-Allow-Origin' 标头的值不能是通配符 '*'...”
问题描述
我在 NodeJS 中有一个 CORS 错误
"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."
我把它放在我的 server.js 中,但仍然出现错误:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:3000");
res.header("Access-Control-Allow-Credentials", true);
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
next();
});
有人可以帮我吗?谢谢
解决方案
这是安全的一部分,你不能这样做。如果您想允许凭据,那么您的 Access-Control-Allow-Origin 不得使用 *. 不过,如果您想允许所有域,您可以简单地添加req.header('Origin')
而不是*
.
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", req.header('Origin'));
res.header("Access-Control-Allow-Credentials", true);
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
next();
});
推荐阅读
- reactjs - 根据条件改变状态
- elasticsearch - 使用摄取管道的 Elastich 搜索翻转索引
- php - PSR-12 - 方法链、换行和缩进
- android - Retrofit 如何处理来自拦截器的无效响应?
- html - 默认展开时使用 Bootstrap 面板显示正确的向上/向下箭头
- css - 为什么我的背景没有像预期的那样剪切到文本?
- python - Python:使用 Jupyter Notebook 运行代码(在线)
- android - 从 Android Studio 清单中的 aar 指定服务
- azure - Azure blob 软删除和版本控制 - 如何轻松还原文件?
- font-awesome - 在日历脚本中添加带有令人敬畏的字体的振动图标