gpt4 book ai didi

express - 在 Create React App 实用程序中启用 CORS

转载 作者:行者123 更新时间:2023-12-04 06:53:38 25 4
gpt4 key购买 nike

我需要使用 CORS React 中的节点模块使用 create-react-app 创建效用。

由于它是一个实用程序,我无法在内部进行调整并注入(inject) CORS 进入预配置 express 模块。

我们怎样才能做到这一点?

最佳答案

如果您需要它进行开发并希望从您的 React 应用程序访问 api 但收到这样的错误-

Failed to load http://localhost:8180/tables: 
The 'Access-Control-Allow-Origin' header has a value 'http://localhost:8180'
that is not equal to the supplied origin. Origin 'http://localhost:3000' is
therefore not allowed access. Have the server send the header with a valid
value, or, if an opaque response serves your needs, set the request's mode to
'no-cors' to fetch the resource with CORS disabled.

然后你可以很容易地让 create-react-app 服务器将你的请求代理到你的 api 服务器。

create-react-app 使用 webpack 开发服务器来为你的 react 应用程序提供服务。

因此,如果您的 react 应用程序是从 http://localhost:3000 提供的您要连接的 api 位于 http://localhost:8180/tables您可以简单地添加 proxy像这样将值放入您的 react 应用程序的 package.json 文件中-
proxy: "http://localhost:8180",

然后从你的 react 应用程序调用你的api
fetch('/tables').then(....)

该请求将被发送到 create-react-app 服务器,该服务器会将其发送到 api 服务器并为您返回结果。

完整的细节在这里 Proxying API Requests in Development

关于express - 在 Create React App 实用程序中启用 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47902840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com