简体   繁体   中英

Can't reverse proxy Node backend using Nginx

I'm working with Angular11 + NodeJS on AWS EC2.

I'm trying to set up a reverse proxy using 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;
    }

}

node: (running on 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}`));

When trying to login @ homepage:

error:

 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

I didn't undertand this reverse proxy at all, I thought I should point my app routes. Thanks!

You just need this much:

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;
    }   
}

You would need to set up different location blocks only if they are going to be handled by a different server, probably running on a different port.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM