不允许 CORS 原始请求 React Express

Posted

技术标签:

【中文标题】不允许 CORS 原始请求 React Express【英文标题】:CORS Origin Request not allowed React Express 【发布时间】:2020-05-25 13:31:21 【问题描述】:

我正在使用 react & express 作为一个简单的表单 当我将我的反应表单发布到快递服务器时,我得到了这个

Access to XMLHttpRequest at 'http://localhost:4000/api/user' from origin 'http://localhost:9000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

这就是我在我的 express server.js 中尝试过的

const cors = require("cors");

app.use(
  cors(
    origin: "*",
    credentials: true
  )
);

在我的中间人

app.use((req, res, next) => 
  res.header("Access-Control-Allow-Origin", "localhost:9000");
  res.header("Access-Control-Allow-Credentials", true);
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
);

我尝试通过 axios 发布请求:

axios
 .post("http://localhost:4000/api/user", data)
 .then(() => console.log("Tadaaa"))
 .catch(err => 
   console.error(err);
);

【问题讨论】:

credential: true 是必需的吗? 不知道,推荐的教程太多了 【参考方案1】:

通过在路由前传递app.use(cors()); 修复了错误

【讨论】:

【参考方案2】:

具有credentials: true 的CORS 请求将不适用于origin: "*"。如果您希望包含凭据,则需要指定您的来源,这也不适用于 localhost。因此,除非您的应用程序是在线托管的,否则我建议不要包含凭据。

有关 CORS 及其工作原理的更多信息,请参阅 here。

【讨论】:

我试过这个:app.use(cors( origin: "*" )); 仍然有同样的错误:( 你可以试试这个:` res.header('Access-Control-Allow-Origin', 'localhost:[your port]'); res.header('Access-Control-Allow-Credentials', true); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');` 在使用 localhost 时,我在某些浏览器(尤其是 Chrome)中遇到了问题。但你可以试一试。对不起格式,似乎无法在 cmets 中制作代码块。 仍未修复 :(( 奇怪,错误还是一样吗? app.use(function(req, res, next) res.header('Access-Control-Allow-Origin', 'localhost:3000'); res.header('Access-Control-Allow-Credentials', true); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); next(); 尝试使用这个中间件函数而不是 app.use(cors),这是我为我的项目设置的功能,使其与本地主机服务器和客户端一起工作。 还是一样 =(((【参考方案3】:

api 用户端点是否存在?否则,请尝试在没有额外选项的情况下传递 cors 中间件。

【讨论】:

是的,我做了``app.use(cors()); `` 上面有错误 + `` 错误:网络错误 `` 终点存在吧?并且服务器也在运行?如果端点不存在,有时您会收到该错误 是的,服务器在 4000 端口上运行,并在 9000 上做出反应,所有 get 请求都可以正常工作 您可能需要发布更多代码,因为我不确定您为什么会从我看到的代码中得到该错误。

以上是关于不允许 CORS 原始请求 React Express的主要内容,如果未能解决你的问题,请参考以下文章