CORS请求,Content-Type:application / json

问题描述 投票:-1回答:1

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

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'.

我的代码是:React Component

    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();
});

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

提前致谢。

reactjs cors
1个回答
-1
投票

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

然后服务器需要使用正确的标头响应:

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

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

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

如果仅用于开发目的,您可以在禁用Web安全性的情况下运行chrome:

Mac:open -a Google\ Chrome --args --disable-web-security --user-data-dir=""

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

© www.soinside.com 2019 - 2024. All rights reserved.