将Angular 4 app静态资产转发到/ PORT路径而不是主域
我们有一个Angular 4应用程序,它是来自exposed + Node应用程序内部的Express,因此它是作为普通节点应用程序启动的。有点像:node index.js
这在本地机器上完成时效果很好。角度应用程序从/client
目录提供:
app.use(express.static(__dirname + "/client"));
当这个项目部署到某个服务器时,express perfectly responses与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基于these tutorials。
转发端口:
nginx可以使用以下规则执行反向代理:
- 任何像appUrl/port这样的请求都应在内部路由到localhost:port
- 在 -
Angular4AndNodeApp
应用程序在PORT 8080
启动(参考部署过程:第7点) - 因此,对 FORWARDED到https://localhost:8080/
调试信息:
- 当我们点击,它命中到节点服务器并返回
client/index.html
文件 - 200 OK client/index.html
文件有<script>
和<link>
标签错误地击中://angular4AppDomain/8080/ - 404未找到
Deployment process:
- 应用程序使用git pull加载到服务器上
- 转到app目录
cd app
- 转到Angular 2应用程序目录
cd client
- 安装Angular 2依赖项
npm i
- 编译Angular 2项目
npm run tsc:w
- 回到app目录
cd ..
- 运行命令
PORT=8080 pm2 start index.js --name=Angular4AndNodeApp
正如所建议的那样,<base href="/">
is set和我们正在访问virtual path。然而,我们没有击中.html,而是击中了.html。
在这个项目中,所有Angular 4组件都是404。
这可能会发生,可能是因为应用程序没有正确编译。
我们如何确保所有这些静态资产都有<script>
和<link>
标签错误地击中/,而是打到/?
这是一个快速演示:
git clone
这个样本回购使用angular-cli https://github/sunilbandla/msal-angular-samplecd
进入文件夹。ng build --base-href /PORT/
- 全局安装节点模块
liter-server
并从项目的根目录运行lite-server
命令 - 打开下面的链接,你可以看到它与网址中的路径一起工作正常。
- http://localhost:3000/PORT/index.html