【问题标题】:How can I properly configure nginx to work with NG Serve and Angular CLI?如何正确配置 nginx 以使用 NG Serve 和 Angular CLI?
【发布时间】:2018-04-06 16:45:23
【问题描述】:

我一直在尝试研究 Nginx 以在 localhost:4200 上配置具有 Angular 5 ng 服务的代理,但只提供服务已构建项目的结果。我从这项研究中发现的配置“有点”有效,但会导致出现未加载任何数据的白页:

dev:12 GET http://192.168.1.84/inline.bundle.js net::ERR_ABORTED
dev:12 GET http://192.168.1.84/polyfills.bundle.js net::ERR_ABORTED
dev:12 GET http://192.168.1.84/styles.bundle.js net::ERR_ABORTED
dev:12 GET http://192.168.1.84/vendor.bundle.js net::ERR_ABORTED
dev:12 GET http://192.168.1.84/main.bundle.js net::ERR_ABORTED

它似乎看不到 ng serve 提供的文件,但至少可以到达项目的 index.html 页面。这是我目前使用的配置:

location /dev {
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        rewrite ^/(.*)$ /$1 break;
        proxy_set_header Host localhost;
        proxy_pass http://localhost:4200;
}

我应该在 /dev 配置中添加什么?

【问题讨论】:

    标签: angular nginx


    【解决方案1】:

    首先,检查 Angular 应用的 <base> 标签 - 它需要与应用的新位置相匹配。因此,例如,如果您通过 nginx 在https://localhost/dev/ 托管您的应用程序,您的<base> 标签将需要:

    <base href="/dev/">
    

    您可以在应用的index.html 中找到此标签。

    其次,nginx 不会自动代理 ng serve 用于实时重载功能的所有流量。您可以通过将其添加到您的 nginx.conf 来代理此额外流量:

    location ^~ /sockjs-node/ {
    
        proxy_pass http://127.0.0.1:4200;
    
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
    
        proxy_http_version 1.1;
        proxy_cache_bypass $http_upgrade;
    }
    

    这假设 ng serve 在端口 4200 上托管您的应用程序(这是默认值)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-19
      • 1970-01-01
      • 2016-11-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多