加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

express – 在create-react-app中启用CORS

发布时间:2020-12-15 20:13:15 所属栏目:百科 来源:网络整理
导读:我需要在使用create-react-app实用程序创建的React中使用’CORS’节点模块. 由于它是一个实用程序,我无法调整内部并将’CORS’注入预先配置的’EXPRESS’模块. 我们怎样才能做到这一点? 解决方法 如果你需要这个用于开发并希望从你的反应应用程序访问api但
我需要在使用create-react-app实用程序创建的React中使用’CORS’节点模块.

由于它是一个实用程序,我无法调整内部并将’CORS’注入预先配置的’EXPRESS’模块.

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

解决方法

如果你需要这个用于开发并希望从你的反应应用程序访问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开发服务器为您的反应应用程序提供服务.

因此,如果您的反应应用程序是从http:// localhost:3000提供的,并且您要连接的api位于http:// localhost:8180 / tables,则只需将代理值添加到您的react应用程序的package.json文件中像这样-

proxy: "http://localhost:8180",

然后从你的反应应用程序调用你的API

fetch('/tables').then(....)

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

详细信息在这里Proxying API Requests in Development

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读