Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 将客户端和服务器部署到同一个VM_Reactjs_Ubuntu_Nginx_Web Applications_Client Server - Fatal编程技术网

Reactjs 将客户端和服务器部署到同一个VM

Reactjs 将客户端和服务器部署到同一个VM,reactjs,ubuntu,nginx,web-applications,client-server,Reactjs,Ubuntu,Nginx,Web Applications,Client Server,我有一个应用程序,它有一个React前端和一个Python Flask后端。前端与服务器通信以执行特定操作,服务器api应仅由客户端使用 我已经将整个应用程序(客户端和服务器)部署到Ubuntu虚拟机上。该机器只对公众开放特定端口(5000、443、22)。我有设置Nginx配置,可以通过http://:5000从浏览器访问前端。服务器在另一个端口(4000)上本地运行,按照设计,公众无法访问该端口 问题是当我访问客户端应用程序并导航到通过与服务器通信的页面时http://127.0.0.1:4

我有一个应用程序,它有一个
React
前端和一个
Python Flask
后端。前端与服务器通信以执行特定操作,服务器api应仅由客户端使用

我已经将整个应用程序(客户端和服务器)部署到Ubuntu虚拟机上。该机器只对公众开放特定端口(5000、443、22)。我有设置
Nginx
配置,可以通过
http://:5000
从浏览器访问前端。服务器在另一个端口(4000)上本地运行,按照设计,公众无法访问该端口

问题是当我访问客户端应用程序并导航到通过
与服务器通信的页面时http://127.0.0.1:4000
从react应用程序中,我收到一个错误消息,说连接被拒绝。
GEThttp://127.0.0.1:4000/ 在我的浏览器上,错误连接被拒绝

当我ssh到vm中并通过curl
curl运行相同的命令时http://127.0.0.1:4000/
,我得到了回复,一切正常


有没有一种方法可以将服务器部署在同一个vm中,这样当我从浏览器访问客户端React应用程序时,React应用程序可以毫无问题地访问服务器?

因此,在修补了这个问题后,我找到了使用Nginx的解决方案。概要是您在本地运行服务器并使用不同的端口,例如4000(不公开),然后在公开的端口上公开您的react应用程序,在本例中为5000

然后在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://:5000/api/endpoint
从浏览器访问端点

您可以通过让客户端向服务器发送令牌来缓解这种情况,如果没有该令牌/授权,服务器将不会运行任何命令

我在这里找到了解决方案,并对其进行了修改,以满足我在这里的具体需要

可以找到解决方案中的其他系列,并