【问题标题】:Unhandled Rejection (Error): A cross-origin error was thrown. - ReactJs未处理的拒绝(错误):引发了跨域错误。 - ReactJs
【发布时间】:2021-05-14 17:47:09
【问题描述】:

我的 React 应用程序遇到了一个奇怪的问题。每当我设置状态变量的值时,应用程序都会抛出以下错误:

Unhandled Rejection (Error): A cross-origin error was thrown. React doesn't have access to the actual error object in development. See https://reactjs.org/link/crossorigin-error for more information.

我正在使用以下配置在服务器端运行 Node.js:

const express = require('express');
const cors = require('cors')({ origin: '*' });

const app = express();
app.use(cors);

app.get('/v1/products', (request, response) => {
    response.send(JSON.stringify(onlineStoreProducts));
});

它会根据请求返回以下标头:

access-control-allow-headers: "Origin, X-Requested-With, Content-Type, Accept"
access-control-allow-origin: "*"
content-encoding: "gzip"
content-type: "text/html; charset=utf-8"
date: "Thu, 11 Feb 2021 00:04:11 GMT"
etag: "W/"521-MMsS1cPRJzAF2U2F3Sjg90rr4Q0""
vary: "Accept-Encoding"
x-powered-by: "Express"

从客户端,我使用 Axios 使用以下代码请求服务器:

axios.get(BASE_URL + '/v1/products').then((response) => {
    console.log(response);
    updateProducts(response.data);
});

函数updateProducts(products)有如下定义:

const [products, setProducts] = useState(null);

const updateProducts = (products) => {
    setProducts(products);
};

现在,只要这个钩子被执行,它就会抛出错误。我怎么知道setProducts(products); 正在抛出错误?我将其更改为 setTimeout(() => setProducts(products).bind(this), 5000); 并导致在获得响应 5 秒后导致错误(我打印了日志)。我什至尝试将其更改为setProducts(JSON.stringify(products));,这也防止了错误。

我明白为什么会发生 CORS 错误,这就是为什么我将服务器配置为在标头中包含 *,但是,由于实际的 CORS 概念,这个错误似乎没有发生。

我在这里遗漏了什么吗?如果需要更多详细信息,请告诉我。

【问题讨论】:

  • 尝试在您的 axios req 上添加 .catch 并记录错误。记录响应时会得到什么?可能检查状态码。
  • 它没有进入 catch 块。 Axios 请求成功。我从服务器收到 200 响应,控制台甚至成功打印 response.data。问题绝对与服务器-客户端网络无关。它与 react-hooks 有关,我只是不知道。
  • 我遇到了同样的问题。没有做任何不寻常的事情,只是一个获取请求和状态更新。出于某种原因,即使请求返回正确的响应,也会出现相同的错误。

标签: node.js reactjs react-hooks cross-domain


【解决方案1】:

我刚刚遇到了同样的问题。问题是我从服务器得到了错误的响应(表行数组而不是单行),因此数据与我的状态结构不兼容。

为什么 React 会抛出一个我不知道的奇怪错误。

【讨论】:

    猜你喜欢
    • 2018-10-16
    • 2021-02-19
    • 2017-06-08
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 2019-10-27
    • 2017-04-04
    • 1970-01-01
    相关资源
    最近更新 更多