【问题标题】:Configure nginx for both Vue app front end and node.js backend为 Vue 应用程序前端和 node.js 后端配置 nginx
【发布时间】:2019-05-10 21:32:38
【问题描述】:

我几个月来一直在寻找这个答案,但一直无法解决这个问题。我使用 nginx 作为我的 web 服务器,使用 node.js 作为我的后端 apis 和 vue 作为我使用 webpack 的主要前端网页。我希望能够通过转到 http://ip 来访问我的 Vue 页面,然后通过转到 http://ip/api 来访问 api 服务。我没有设置域名,所以我使用 IP 地址作为 url。

到目前为止,我构建了我的 Vue 应用程序并位于 /var/www/html/Web/dist 文件夹中,如果您转到 http://ip url,它可以工作,但我无法访问我的 node.js API。我的 node.js 服务器在 localhost 端口 3000 上运行。我的 nginx 配置如下所示:

server {
        listen 80;

        root /var/www/html/Web/dist;
}

server {

listen 80;

  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;

  }

}

【问题讨论】:

    标签: node.js nginx vue.js


    【解决方案1】:

    您正在复制服务器配置。只需设置一个服务器属性即可:

    server {
      listen 80;    
      root /var/www/html/Web/dist;
      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;
    
      }
    }
    

    这意味着:

    • 监听 80 端口上所有 ip 的所有请求
    • 从根/var/www/html/Web/dist; 评估相对路径
    • 如果 url 中有匹配的 '/api/' 将其传递给 localhost:3000

    现在应该可以正常工作了

    【讨论】:

    • 根据节点应用架构,可能需要将proxy_pass http://localhost:3000; 替换为proxy_pass http://localhost:3000/ 以将请求URI 从/api/route/path/ 重写为/route/path/
    猜你喜欢
    • 1970-01-01
    • 2020-04-06
    • 2021-05-19
    • 2019-03-11
    • 2019-09-17
    • 2013-05-11
    • 2020-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多