【问题标题】:Can't reverse proxy Node backend using Nginx无法使用 Nginx 反向代理节点后端
【发布时间】:2021-06-13 00:09:39
【问题描述】:

我正在 AWS EC2 上使用 Angular11 + NodeJS。

我正在尝试使用 nginx 设置反向代理。

nginx:

server {
    listen 80;
    listen [::]:80;
    server_name http://MY-AWS-IP.com;
    root /home/ubuntu/dashboard/frontend/dist/frontangular;
    server_tokens off;
    index index.html index.htm;

location /auth/ {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
location /groceries/ {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

}

节点:(在 pm2 上运行)

... Some stuff
const ports = process.env.PORT || 3000;

app.use("/groceries", groceryRoutes);
app.use("/auth", loginRoutes);

app.listen(ports, () => console.log(`listening on port ${ports}`));

尝试登录@主页时:

错误:

POST http://localhost:3000/auth/login net::ERR_CONNECTION_REFUSED
ERROR 
kd {headers: dd, status: 0, statusText: "Unknown Error", url: "http://localhost:3000/auth/login", ok: false, …}
error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", …}
headers: dd {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
message: "Http failure response for http://localhost:3000/auth/login: 0 Unknown Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "Unknown Error"
url: "http://localhost:3000/auth/login"
__proto__: wd

我根本不了解这个反向代理,我想我应该指出我的应用程序路线。 谢谢!

【问题讨论】:

  • 你的代理80到本地3000,3000没有服务器
  • 我想我在 3000 上运行我的节点。我正在使用 const ports = process.env.PORT || 3000;并在 pm2 上运行它
  • 当然,但 Nginx 没有监听 3000,因此连接被拒绝,您需要从客户端代码中删除 3000,而只需使用 80(或完全从客户端删除端口的想法)

标签: node.js angular nginx amazon-ec2


【解决方案1】:

你只需要这么多:

server {
    listen 80;
    listen [::]:80;
    server_name http://MY-AWS-IP.com;
    root /home/ubuntu/dashboard/frontend/dist/frontangular;
    server_tokens off;
    index index.html index.htm;

    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }   
}

只有当它们将由不同的服务器处理时,您才需要设置不同的位置块,可能在不同的端口上运行。

【讨论】:

  • 哦,明白了!它仍然无法正常工作,所以我可能还有其他问题,您有什么想法吗?谢谢!!
  • 您的 Node 应用程序是否正常运行?你可以在localhost:3000 上卷曲它吗?
  • 我用 sudo 运行它,我认为这是“连接被拒绝”的原因。现在我只是'npm start','curl localhost:3000' 返回:{"error":{"message":"Not found"}}。并从浏览器访问它,在 DOM 中返回相同的消息。我们到了那里,但仍然没有工作:(