我有一个具有React前端和Python Flask后端的应用程序。前端与服务端进行通信,执行特定的操作,服务端api应仅供客户端使用。
我已经将整个应用程序(客户端和服务器)部署到了Ubuntu虚拟机上。机器只有特定的端口对公众开放(5000、443、22)。我有设置Nginx配置和前端可以通过http://<ip:address>:5000从我的浏览器访问。服务器在本地的另一个端口4000上运行,按照设计,公众无法访问该端口。
问题是,当我访问客户端应用程序,并从react应用程序导航到通过http://127.0.0.1:4000与服务器通信的页面时,我收到一个错误消息,说连接被拒绝。我的浏览器上的GET http://127.0.0.1:4000/ net::ERR_CONNECTION_REFUSED。
当我通过ssh进入vm并通过curl curl http://127.0.0.1:4000/运行相同的命令时,我得到了一个响应,并且一切正常。
有没有一种方法可以将服务器部署在同一个vm中,以便当我从浏览器访问客户端React App时,React App可以毫无问题地访问服务器?
发布于 2020-09-26 14:18:46
所以在修改之后,我找到了一个使用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://<ip:address>:5000/api/endpoint从浏览器访问端点
您可以通过让客户端向服务器发送令牌来缓解此问题,并且服务器在没有该令牌/授权的情况下不会运行任何命令。
我在这里找到了解决方案,并对其进行了修改,以满足我在这里的特定需求Part two of solution
该解决方案中的其他系列可以在Part one of solution和Part three of solution中找到
https://stackoverflow.com/questions/64071223
复制相似问题