Angular 4 CLI应用程序

时间:2017-08-28 11:18:19

标签: angular nginx webserver angular-cli nginx-location

我一直在挖掘stackoverflow-answers和github问题几个小时,但我还是找不到合适的解决方案。

我有一个使用Angular-CLI构建的Angular 4应用程序。 我想从http://XYZ:80/angularapp的nginx服务器(在Docker容器内)提供此应用程序。

为了拥有此应用程序范围的base-href,我使用ng build --base-href /angularapp构建了应用程序,将<base href="/angularapp">添加到index.html文件夹中的dist

对于部署,我已将dist的内容复制到/usr/share/nginx/html,我的nginx配置如下所示:

server {
    listen       80;
    server_name  localhost;

    location /api {
        # adjust port of backend to desired port
        proxy_pass http://backend:8081;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
    }

    location / {
        root  /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html$is_args$args;
    }
}

这非常正常,我可以转到http://XYZ:80/angularapphttp://XYZ:80/(将重定向到/angularapp)来访问该应用。

现在,我尝试从其他域(例如http://my-intranet/app)链接此应用,该域还应显示http://XYZ:80/angularapp的内容。 但是,这会导致问题,因为所有资产都有错误的请求路径(例如http://my-intranet/main.f574d09ce6036fc0840e.bundle.js)。因此,我收到错误Uncaught SyntaxError: Unexpected token <

我尝试使用--deploy-url /angularapp--deploy-url .,这会破坏原始应用网址(http://XYZ:80/angularapp)。

有人可以提供有关如何正确配置此案例的nginx位置的帮助吗?提前谢谢!

1 个答案:

答案 0 :(得分:0)

当您在angular-cli中使用nginx的try_files指令和--base-href时。它会造成问题。

当nginx遍历你的index.html并看到styles.xxx.bundle.css,inline.xxx.bunble.js和各种其他包的链接时。

--base-href将/angularapp/styles.xxx.bundle.css和/angularapp/inline.xxx.bunble.js附加到链接并且nginx尝试执行位置块并执行try_files指令将URI重定向到index.html。

这就是你看到

的原因
  

未捕获的SyntaxError:意外的标记&lt;

要避免这种情况,您应该使用--deploy-url并使文件夹路径与--base-href--deploy-url同名,例如/ usr / share / nginx / html / angularapp /并复制那里的dist文件夹。

然后该应用将以其他方式移除try_files或不使用--base-href