CORS请求,内容类型:application / json

时间:2019-03-11 14:58:26

标签: reactjs cors

我正在使用具有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'.

我的代码是: 反应组件

    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时说{ // See https://go.microsoft.com/fwlink/?LinkId=733558 // for the documentation about the tasks.json format "version": "2.0.0", "tasks": [ { "type": "typescript", "tsconfig": "tsconfig.json", "problemMatcher": [ "$tsc" ], "group": { "kind": "build", "isDefault": true } } ] } 。 >

谢谢。

1 个答案:

答案 0 :(得分:-1)

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

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

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

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

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

如果仅出于开发目的,您可以在禁用网络安全性的情况下运行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