我有一个 AWS Ubuntu 服务器,它托管在 127.0.0.1:4100 运行的 React 前端,并使用端口 127.0.0.1:1323 对 Go 应用程序进行 api 调用。我安装了 Nginx 并为这两个端口设置了代理通行证/etc/nginx/sites-available/default
配置文件,但我只得到 Nginx 调用的前端。使用 chrome 检查检查 Go 应用程序为何不提供 React 应用程序的某些功能,我看到此错误
client.js:772 获取http://127.0.0.1:1323/api/净::ERR_CONNECTION_REFUSED
ERROR 错误:请求已终止 可能原因:网络离线、Access-Control-Allow-Origin 不允许 Origin、页面正在卸载等。
我究竟做错了什么?下面是我的默认配置文件
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
location / {
proxy_pass http://127.0.0.1:4100;
}
location /api {
proxy_pass http://127.0.0.1:1323/;
}
}
您的服务器正在监听 80 端口:
listen 80 default_server;
listen [::]:80 default_server;
因此,您应该向该端口发出请求:
GET http://127.0.0.1/api/ => http://127.0.0.1:1323/
GET http://127.0.0.1:80/api/ => http://127.0.0.1:1323/
GET http://127.0.0.1/ => http://127.0.0.1:4100/
GET http://127.0.0.1:80/ => http://127.0.0.1:4100/
那么 nginx 应该正确代理你的请求。
Update
更清楚地了解 nginx 配置。
server {
listen 80 default_server; // The port nginx is listening to ipv4
listen [::]:80 default_server; // The port nginx is listening to ipv6
server_name _;
location / { // When you call this location...
proxy_pass http://127.0.0.1:4100; // You'll be redirected to this location
}
location /api { // When you call this location...
proxy_pass http://127.0.0.1:1323/; // You'll be redirected to this location
}
}
你的配置没问题根据 nginx 文档.
你说你的客户正试图联系http://127.0.0.1:1323/api/
但应该要求http://127.0.0.1/api/
(不带端口)重定向到http://127.0.0.1:1323/
.
这是另一个例子:
server {
listen 80;
server_name localhost anywebsite.com;
location ~* ^/MyApp {
proxy_pass http://localhost:5130;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_send_timeout 2m;
proxy_read_timeout 2m;
}
}
在这种情况下,每次我的网址以/MyApp
ex.: http://anywebsite.com/api/MyApp
我被代理到http://localhost:5130
。但如果我尝试访问http://localhost:5130
or http://anywebsite.com:5130/api/MyApp
我不能,因为 nginx 仅监听端口 80。如果你想访问另一个端口,你需要这样指定:
server {
listen 80;
listen 5130;
[...]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)