我有一个具有 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 solution和 Part three of solution
关于reactjs - 将客户端和服务器部署到同一个虚拟机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64071223/