o1sound o1sound - 17 days ago 5
Node.js Question

trouble getting a file from node.js using nginx reverse proxy

I have set up an nginx reverse proxy to node essentially using this set up reproduced below:

upstream nodejs {
server localhost:3000;
}

server {
listen 8080;
server_name localhost;
root ~/workspace/test/app;

location / {
try_files $uri $uri/ @nodejs;
}

location @nodejs {
proxy_redirect off;
proxy_http_version 1.1;
proxy_pass http://nodejs;
proxy_set_header Host $host ;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}


Now all my AJAX POST requests travel just fine to the node with this set up, but I am polling for files afterward that I cannot find when I make a clientside AJAX GET request to the node server (via this nginx proxy).

For example, for a clientside javascript request like
.get('Users/myfile.txt')
the browser will look for the file on
localhost:8080
but won't find it because it's actually written to
localhost:3000


http://localhost:8080/Users/myfile.txt // what the browser searches for
http://localhost:3000/Users/myfile.txt // where the file really is


How do I set up the proxy to navigate through to this file?

Answer

Okay, I got it working. The set up in the nginx.conf file posted above is just fine. This problem was never an nginx problem. The problem was in my index.js file over on the node server.

When I got nginx to serve all the static files, I commented out the following line from index.js

app.use(express.static('Users')); // please don't comment this out thank you

It took me a while to troubleshoot my way back to this as I was pretty wrapped up in understanding nginx. My thinking at the time was that if nginx is serving static files why would I need express to serve them? Without this line however, express won't serve any files at all obviously.

Now with express serving static files properly, nginx handles all static files from the web app and node handles all the files from the backend and all is good.

Thanks to Keenan Lawrence for the guidance and AR7 for the config!