【问题标题】:ReactJS with Express Server CORS setup [closed]带有 Express Server CORS 设置的 ReactJS [关闭]
【发布时间】:2020-08-09 00:51:55
【问题描述】:

尽管关于 CORS 问题提出了很多问题,但没有一个对我有帮助。首先,我了解 CORS 是什么以及为什么它很重要。

我不想禁用 CORS。我想正确使用它。

我有一个在 http://localhost:3000 上运行的 ReactJS 应用程序。我的后端 NodeJS 应用程序也在 http://localhost:1234 上运行。

我已经从我的 NodeJS 应用程序中启用了 CORS,如下所示:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "http://localhost:3000") // update to match the domain you will make the request from
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
  next()
});

这就是我的请求在 ReactJS 应用程序中的样子:

axios
    .post(this.props.endPoint, formData)
    .then(res => {
        console.log("Successfull");
        this.setState({
            loginOk: true
        });
    })
    .catch(err => {
        console.log(err);
    });

这是登录页面。当我提交请求时,我在浏览器控制台中看到以下错误。

Access to XMLHttpRequest at 'http://localhost:1234/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

更新

我发现我调用的 REST 端点是完全错误的。修复它解决了这个问题。

总结

如果您有我在问题中描述的这种设置,它应该可以正常工作。另外,我会选择 @T.J. 的备用库。 Crowder 建议在我的 NodeJS 应用中使用。

【问题讨论】:

  • OPTIONS(飞行前)响应返回什么状态? (您可能需要 Fiddler 或类似工具才能找到。)

标签: javascript node.js reactjs express cors


【解决方案1】:

问题可能是您使用next 链接到的后续路由没有意识到他们正在处理OPTIONS 请求(预检)。对预检的响应应该是标题。

如果是这样,您可以这样修复它:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "http://localhost:3000") // update to match the domain you will make the request from
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
  if (req.method === "OPTIONS") {
    res.status(200).end();
  } else {
    next()
  }
});

...前提是中间件优先于其他,等等

也就是说,您可能会查看久经考验的中间件,而不是自行开发。 cors 似乎很受欢迎。

【讨论】:

  • 感谢您的回答。您的第一点帮助我发现我在 ReactJS 中调用的请求路径是完全错误的。其次,使用cors 库会非常简洁。再次 +1!
猜你喜欢
  • 1970-01-01
  • 2020-10-25
  • 1970-01-01
  • 2021-03-17
  • 2019-06-26
  • 1970-01-01
  • 2019-08-26
  • 1970-01-01
  • 2021-04-04
相关资源
最近更新 更多