代码之家  ›  专栏  ›  技术社区  ›  jedi

使用Rails应用程序和Vue.js应用程序设置nginx+乘客

  •  2
  • jedi  · 技术社区  · 6 年前

    我有一个带有乘客的nginx远程服务器,它通过公共IP 12.34.56.78为我的Rails API提供服务。

    现在,我已经将一个Vue.js应用程序部署到同一个主机上,并且可以通过输入IP地址12.34.56.78从浏览器访问该应用程序,但是当我尝试登录时,我得到并出错。 CONNECTION REFUSED

    这是我的 nginx.conf

    Rails应用程序

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

    JUP应用程序

    server {
            listen   80 default_server;
            server_name  bikeramp_front.local;
    
            location / {
                root   /home/jdomanski/bikeramp-front;
                try_files $uri $uri/ /index.html;
            }
        }
    

    我已经确认我的两个应用程序都由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    
    

    我可以从IP地址12.34.56.78/sign in访问我的vue.js应用程序,但是当我从前端登录表单发出HTTP请求时,我会收到一个错误。

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

    这是我向API发出HTTP请求的代码

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

    当我通过指向远程IP从本地计算机的前端发出请求时,我现在得到一个错误:

    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.

    如何配置nginx,使其从前端应用程序向后端应用程序发出请求,该应用程序位于同一台nginx服务器所服务的同一主机上。我可能在我的 NGNX.CONF 文件。你能帮助我吗?我应该在nginx启用cors吗?

    1 回复  |  直到 6 年前
        1
  •  3
  •   Mihai Târnovan    6 年前

    你是从一个不同的领域为前端服务,所以,是的,你需要有许可的CORS Access-Control-Allow-Origin (或 * 或者在dev中使用的域)。

    编辑:您可以使用nginx或rails(例如 https://github.com/cyu/rack-cors )