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

编程入门 行业动态 更新时间:2024-10-17 07:26:05
本文介绍了在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.

我们如何实现此目标?

推荐答案

如果您需要此功能进行开发并希望从您的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 localhost:8180/tables: The 'Access-Control-Allow-Origin' header has a value 'localhost:8180' that is not equal to the supplied origin. Origin '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 localhost:3000 and the api you want to connect to is at localhost:8180/tables you can simply add a proxy value into your react app's package.json file like this-

proxy: "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

本文发布于:2023-11-24 20:43:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1626755.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实用程序   React   Create   CORS   App

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!