繁体   English   中英

使用在本地主机上运行的 API 从反应应用发出 http 请求

[英]Making an http request from react app with API running on localhost

On my main PC I have a react app running http://localhost:3000 , aswell as a nodejs and express API http://localhost:3001 , so my react app requests the data from the API that is running on the same machine它工作正常,它加载 web 应用程序并成功发出 http 请求。 我现在想从另一台计算机访问反应应用程序,所以当我访问我的反应应用程序时,使用我的主计算机内部 IP,反应应用程序加载得很好,但是 API 请求失败。 In console I get GET http://localhost:3001/today net::ERR_CONNECTION_REFUSED , when making my axios request I dont refer to the API as http://localhost:3001 I use the public IP of my computer instead of localhost,我也进入了我的路由器并转发了端口 3000 和 3001。所以在我看来,即使我在另一台计算机上,react 应用程序仍然认为它在 localhost 上。 我怎样才能解决这个问题?

当我端口转发端口 3000 和 3001 时,我忘记将协议从 tcp 更改为 tcp/udp。 当我同时使用 TCP 和 UDP 进行端口转发时,它工作正常

我认为您正在解决 CORS (跨域资源共享)问题。 我的意思是你有这个错误,因为你的服务器(NodeJS)和你的应用程序(React)在同一台计算机上运行。 所以你需要启用 CORS:

  1. 打开您的 package.json 文件并添加以下属性: “proxy”:“http://localhost:3001” 2)在您的 React 应用程序中,而不是让您的请求获取(“http://localhost:3001/users”)你会像这样发送你的请求fetch("/users")

点击这里阅读更多

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM