-1

我正在开发一个带有 React 前端和节点后端的 Web 应用程序。它们都分别在我的本地计算机上localhost:3000运行localhost:8080。是否可以使用 CORS 请求headers: { "Content-Type": "application/json" }?基于查看其他问题,它似乎是,但我仍然在控制台中收到错误:

Access to fetch at 'http://localhost:8080/chordSheets/0' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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:8080/chordSheets/${id}`, {
      method: 'POST',
      credentials: 'include',
      mode: 'cors',
      body: data,
      headers: {
        "Content-Type": "application/json",
      },
    })

节点设置:

app.use((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, Options");
  res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
  req.login = promisify(req.login, req);
  next();
});

如果我理解正确,这应该允许 CORS 请求,"Content-Type": "application/json" 但我不明白为什么控制台错误The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*'在设置为localhost:3000.

提前致谢。

4

1 回答 1

-1

此错误由浏览器触发。无法通过调整客户端应用程序代码来修复。要解决此问题,您必须让节点服务器处理 OPTIONS 预检请求,当您向与当前运行的网页不同的来源发出 ajax 请求时,该请求由浏览器触发。

然后,服务器需要使用正确的标头对此进行响应:

Access-Control-Allow-Origin: '*'或者'Access-Control-Allow-Origin': 'http://localhost:3000'

您可以将此包添加到您的节点服务器:https ://expressjs.com/en/resources/middleware/cors.html

这将为您完成所有繁重的工作。

如果只是出于开发目的,您可以在禁用网络安全的情况下运行 chrome:

苹果电脑:open -a Google\ Chrome --args --disable-web-security --user-data-dir=""

视窗:chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security

于 2019-03-11T16:08:23.107 回答