在 Create React App 实用程序中启用 CORS [英] Enabling CORS in Create React App utility

查看:25
本文介绍了在 Create React App 实用程序中启用 CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在使用 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.

我们如何才能做到这一点?

How can we achieve this?

推荐答案

如果你在开发中需要这个,并且想要从你的 React 应用程序访问一个 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.

因此,如果您的 React 应用程序是从 http://localhost:3000 提供的,并且您要连接的 API 位于 http://localhost:8180/tables 你可以像这样简单地将 proxy 值添加到你的 React 应用程序的 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",

然后从你的反应应用程序调用你的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆