【发布时间】: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