Search code examples
reactjsruby-on-railsnginxreverse-proxy

How can I connect localhost of the host machine?


I was trying to host react as a frontend and rails as backend.

I host rails at http://localhost:3000.

enter image description here

You can see that it is working.

But when I call http://localhost:3000 from react, instead of going to server's localhost, it go to user's localhost.

enter image description here

How can I fix this? I am using Nginx as web server.


Solution

  • I just solved by doing reverse proxy in Nginx.

    location / {
                try_files $uri /index.html;
        }
    
    
    location /api {  
     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; 
    }
    

    first location / will find static frontend files and /api will go to localhost:3000.

    For example, in my case

    this.url='https://yourdomain.com/api/' to access the backend.

    Also don't forget all of your backend route to start with 'api/'.