【问题标题】:Cannot send request in React App because of CORS, even with CORS enabled on my server由于 CORS,即使在我的服务器上启用了 CORS,也无法在 React App 中发送请求
【发布时间】:2020-05-11 09:35:51
【问题描述】:

这就是我配置服务器的方式

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const morgan = require('morgan');

const app = express();
const port = 3000;

app.use(cors());
app.use(bodyParser.json());
app.use(morgan(':method :url :status :res[content-length] - :response-time ms'));

现在,我想既然我使用了 cors 包,并且我为所有来源启用了它,我的请求将在我的应用程序中通过。嗯,它没有,因为每次我尝试向服务器发送请求时,都会给我一个 CORS 错误。

我正在使用有趣的绕过:我在端口3000(CRA 的端口)上启动我的服务器。如果我先启动服务器,然后启动我的 React 应用程序,CRA 会提示我切换到不同的端口。现在,我可以向我的服务器发送请求,而无需使用 CORS。但是,如何在我的应用中正确启用 CORS?

来自浏览器的完整错误:

TypeError: "NetworkError when attempting to fetch resource.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/accounts. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/accounts. (Reason: CORS request did not succeed).

更新:我有

app.use(function (req, res, next) { 
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
})

在我的服务器中,但由于某种原因,在发送响应时,它没有标头?

【问题讨论】:

  • 你能分享完整的错误吗?在浏览器的控制台中返回。
  • @BENARDPatrick 刚刚编辑了我的代码以获得完整的错误
  • 您的客户端是否在本地主机上运行?
  • 是的,但在不同的端口上
  • 响应的 HTTP 状态码是什么?您可以使用浏览器开发工具中的网络窗格进行检查。是 4xx 还是 5xx 错误而不是 200 OK 成功响应?

标签: node.js reactjs express cors


【解决方案1】:

??‍? 尝试在您的服务器中使用

const cors = require('cors');
app.use(cors({ origin: '*'}));

? 确保,当您从 React 应用程序调用端点时,不要使用:localhost,而是使用:http://localhost

希望对你有帮助?。

【讨论】:

  • 我不知道,为什么它在你的身上不起作用,但在我回答你的问题之前,我先试了一下,它工作正常。
  • 对我来说也很奇怪,它不起作用。您的回答也适用于我的朋友,但对我来说,它返回了 200 OK 响应,但没有返回任何 Access-Control-Allow- 标头
猜你喜欢
  • 2015-02-25
  • 2020-06-04
  • 1970-01-01
  • 2020-03-30
  • 2016-12-02
  • 2021-10-28
  • 2020-10-18
  • 2018-09-10
  • 2019-04-29
相关资源
最近更新 更多