Search code examples
ruby-on-railsnginxvue.jspassenger

Setup Nginx + Passenger with Rails App and Vue.js app


I have an Nginx remote server with Passenger that serves my Rails API over a public IP 12.34.56.78.

Now, I have deployed a Vue.js app to the same host and am able to access the app from the browser by putting in the IP address 12.34.56.78 but when I try to sign in I get and error CONNECTION REFUSED

This is my nginx.conf

Rails app

server {
    listen       3000;
    server_name  bikeramp.local;

    root /home/deploy/bikeramp/current/public;
    passenger_enabled on;
    rails_env production;
    access_log /var/log/nginx/bikeramp.access.log;
    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }
}

Vue.js app

server {
        listen   80 default_server;
        server_name  bikeramp_front.local;

        location / {
            root   /home/jdomanski/bikeramp-front;
            try_files $uri $uri/ /index.html;
        }
    }

I have confirmed both my apps are being served by Nginx:

netstat -tln

tcp        0      0 127.0.0.1:41382         0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:50022           0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:3000            0.0.0.0:*               LISTEN    

I am able to access my Vue.js app from the IP address 12.34.56.78/signin but when I make a HTTP request from the front-end sign in form I get an error

OPTIONS http://localhost:3000/api/users/login net::ERR_CONNECTION_REFUSED

This is the code where I make the HTTP request to the API

axios.defaults.baseURL = 'http://localhost:3000'

When I make the request from front-end on my local machine by pointing to the remote IP I now get an error:

XMLHttpRequest cannot load http://54.38.36.242/api/users/login. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 405.

How can I configure Nginx to make requests from my front end app to the backend app living on the same host served by the same Nginx server. I am probably lacking something in my nginx.conf file. Can you help me? Should I enable CORS in Nginx?


Solution

  • You're serving the frontend from a different domain, so, yes you need CORS with permissive Access-Control-Allow-Origin (either * or the domains you are using in dev).

    Edit: you can use NGINX for this, or Rails (for example https://github.com/cyu/rack-cors)