首页 > 解决方案 > 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();
});

有人可以帮我吗?谢谢

标签: node.jsexpress

解决方案


这是安全的一部分,你不能这样做。如果您想允许凭据,那么您的 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();
});

推荐阅读