将 Angular 4 个应用程序静态资产转发到 /PORT 路径而不是主域

Forward Angular 4 app static assets to a /PORT path instead of main domain

我们有一个 Angular 4 app which is exposed from inside a Node + Express 应用程序,因此作为普通节点应用程序启动。有点像:node index.js

这在本地机器上完成时效果非常好。 angular 应用程序从 /client 目录提供:

app.use(express.static(__dirname + "/client"));

当这个项目部署到某个服务器时,client/index.html 文件:

<html>
<head>
    <title>Angular 4 app</title>
    <base href="/">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="public/styles.css">
    <!-- 1. Load libraries -->
    <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <!-- 2. Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    <script>
        System.import('app').catch(function(err) {
            console.error(err);
        });
    </script>
</head>
<!-- 3. Display the application -->

<body>
    <my-app>
        <h1>Loading...</h1>
    </my-app>
    <script type="text/javascript" src="public/jquery.connectingLine.js"></script>
</body>
</html>

应用模板取自here based on these tutorials

端口转发:

nginx是用来做反向代理的,规则如下:

调试信息:

  1. 应用程序使用 git pull
  2. 在服务器上加载
  3. 进入应用目录cd app
  4. 转到Angular 2个应用程序目录cd client
  5. 安装Angular 2个依赖npm i
  6. 编译Angular2项目npm run tsc:w
  7. 返回应用程序目录cd ..
  8. 运行命令PORT=8080 pm2 start index.js --name=Angular4AndNodeApp

按照建议, and we're accessing the . However, instead of hitting http://example.com/someapp/index.html, we're hitting http://example.com/PORT/index.html

在这个项目中,所有 Angular 4 个组件都是 404s.

发生这种情况可能是因为应用程序未正确编译。

我们如何确保所有这些静态资产都具有 <script><link> 标签,这些标签错误地命中了 https://angular4AppDomain.com/,而不是点击 https://angular4AppDomain.com/8080/?

这是一个快速演示:

  1. git clone 这个示例 repo 使用 angular-cli https://github.com/sunilbandla/msal-angular-sample
  2. cd进入文件夹。
  3. ng build --base-href /PORT/
  4. 全局安装节点模块 liter-server 并从项目的根目录 运行 lite-server 命令
  5. 打开下面的 link 你可以看到它在 url 中的路径下工作正常。
  6. http://localhost:3000/PORT/index.html