reactjs - 将客户端和服务器部署到同一个虚拟机

标签 reactjs ubuntu nginx web-applications client-server

我有一个具有 React 的应用程序前端和 Python Flask后端。前端与服务器通信以执行特定操作,服务器 api 应仅由客户端使用。
我已将整个应用程序(客户端和服务器)部署到 Ubuntu 虚拟机。该机器仅具有向公众开放的特定端口(5000、443、22)。我已设置 Nginx配置和前端可以通过http://<ip:address>:5000从我的浏览器访问.服务器在不同的端口 4000 上本地运行,按照设计,公众无法访问该端口。
问题是当我访问客户端应用程序并导航到通过 http://127.0.0.1:4000 与服务器通信的页面时从 react 应用程序中,我收到一条错误消息,提示连接被拒绝。GET http://127.0.0.1:4000/ net::ERR_CONNECTION_REFUSED在我的浏览器上。
当我 ssh 进入 vm 并通过 curl curl http://127.0.0.1:4000/ 运行相同的命令时,我得到回应,一切正常。
有没有办法可以将服务器部署在同一个虚拟机中,这样当我从浏览器访问客户端 React App 时,React App 可以毫无问题地访问服务器?

最佳答案

所以在修改了这个之后,我找到了一个使用 Nginx 的解决方案。总结是您在本地运行服务器并使用不同的端口,例如 4000(未公开),然后在本例中为 5000 的公开端口上公开您的 react 应用程序。
然后在你的 Nginx 配置中使用一个代理来重定向任何以 api 开头的调用到本地主机服务器运行。见下面的配置

server {
   #Exposed port and servername ipaddress
   listen 5000;
   server_name 1.2.3.4 mydomain.com;

   #SSL
   ssl on;
   ssl_certificate /etc/nginx/ssl/nginx.crt;
   ssl_certificate_key /etc/nginx/ssl/nginx.key;
   ssl_protocols TLSv1.2;

   #Link to the react build   
   root /var/www/html/build;
   index index.html index.htm;

   #Error and access logs for debugging
   access_log /var/log/nginx/access.log;
   error_log /var/log/nginx/error.log;

   location / {
       try_files $uri /index.html =404;
   }

   #Redirect any traffic beginning with /api to the flask server
   location /api {
    include proxy_params;
    proxy_pass http://localhost:4000;
   }
}
现在这意味着您需要让所有服务器端点以 /api/... 开头并且用户也可以通过http://<ip:address>:5000/api/endpoint从浏览器访问端点
您可以通过让您的客户端向服务器发送 token 来缓解这种情况,如果没有该 token /授权,服务器将不会运行任何命令。
我在这里找到了解决方案并对其进行了修改以满足我的特定需求
Part two of solution
解决方案中其他系列可查看Part one of solutionPart three of solution

关于reactjs - 将客户端和服务器部署到同一个虚拟机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64071223/

相关文章:

javascript - Redux saga 永远不会运行

c - GCC 未按预期在 Ubuntu 中编译 C 代码

gcc - 是否可以同时安装 2 个不同版本的 GCC?

docker - Nginx (https) 管理控制台后面的 Keycloak 19.0 无法加载

Nginx与乘客

javascript - React 访问数组映射中的 setState

javascript - 将 mongodb 中的图像保存为 blob,React

php - EC2 用户数据卡在 "Checking init scripts..."ubuntu php

linux - 服务器 LEMP 无响应(CentOS 5.5 final)

reactjs - 我正在尝试使用useEffect'来更改窗口。我没有收到任何错误,但是没有用。怎么了?如何使其运作?