在Create React App实用程序中启用CORS [英] Enabling CORS in Create React App utility
问题描述
我需要在使用 create-react-app
实用工具创建的React中使用 CORS 节点模块。
I need to use CORS node module in React created using create-react-app
utility.
由于使用了实用程序,因此我无法对其进行调整并将 CORS 注入到预先配置的 EXPRESS 模块中。
Since its a utility I am not able to tweak inside and inject CORS into preconfigured EXPRESS module.
我们如何实现此目标?
推荐答案
如果您需要此功能进行开发并希望从您的API访问反应应用程序,但出现这样的错误-
If you are needing this for development and wanting to access an api from your react app but getting an error like this-
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服务器。
then you can get the create-react-app server to proxy your request to your api server quite easily.
create-react-app使用Webpack开发服务器来服务您的React应用。
create-react-app uses the webpack development server to serve your react app.
因此,如果您的从 http:// localhost:3000
提供react应用,您要连接的api在 http:// localhost:8180 /表格
,您只需将 proxy
值添加到您的应用程序的package.json文件中,就像这样-
So if your react app is being served from http://localhost:3000
and the api you want to connect to is at http://localhost:8180/tables
you can simply add a proxy
value into your react app's package.json file like this-
proxy: "http://localhost:8180",
然后从您的react应用程序中调用您的api
then from your react app call your api like
fetch('/tables').then(....)
请求将发送到create-react-app服务器,该服务器将请求发送到api服务器并为您返回结果。
the request will be sent to the create-react-app server which will send it on to the api server and return the results for you.
此处的完整详细信息在开发中代理API请求
这篇关于在Create React App实用程序中启用CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!