【发布时间】:2018-09-30 17:28:21
【问题描述】:
Nodejs 应用程序使用 Express(快速生成器)创建并使用把手作为视图引擎。创建了几条路线并且工作正常。应用程序在 3000 端口上运行。
快速路线:
...
app.use('/', index);
app.use('/landing', landing);
app.use('/home', home);
app.use('/api', api);
...
在 Angular 上构建了一个单独的管理面板应用程序
目前 Angular 应用程序在 4200 端口上运行,并使用 NodeJs 应用程序的 API,该应用程序在 3000 端口上运行。
Angular 应用程序路由
const routes : Routes = [
{ path: '', redirectTo: '/user', pathMatch: 'full' },
{
path: 'user',
component : UserComponent,
children : [
{ path:'', redirectTo: '/account', pathMatch: 'full' },
{ path: 'account', component: AccountComponent },
]
},
]
NodeJs 应用文件夹结构
api/
api.js
bin/
www
modules/
mongoose.js
node_modules/
public/
css/
fonts/
img/
js/
ngapp/ => Angular resources created with ng build
inline.bundle.js
main.bundle.js
polyfills.bundle.js
styles.bundle.js
vendor.bundle.js
routes/
home.js
index.js
landing.js
views/
common/
header.hbs
footer.hbs
layouts/
master.hbs
ngapp/
index.html => Angular index.html file
index.hbs
landing.hbs
home.hbs
app.js
package.json
我正在尝试什么: 想要在同一个端口(即端口 3000)上同时运行 NodeJs 和 Angular 应用程序。
我做了什么: 运行 ng build 并将 index.html 文件放在 nodejs 文件夹结构的 /views/ngapp/ 中。
在 nodejs 中创建了一个 'user' 路由并为 Angular 应用程序的 index.html 文件提供服务。 (可能这不是一个好方法)
app.get('/user', function (req, res, next) {
res.sendFile(path.join(__dirname + '/views/ngapp/index.html'));
});
我的问题是关于我们如何将 Angular 应用程序(可能在单独的路由上但在同一个端口上运行)与已经定义了一些路由并使用视图引擎呈现页面的 NodeJs 应用程序集成。
【问题讨论】:
-
你应该提供目录结构来理解这个
path.join(__dirname + '/views/ngapp/index.html')以及至少包含所有路由的脚本 -
发现 Angular 路由有问题。而不是
/user它应该是user和account相同。现在它的工作。 -
不错,有时候再看一遍就够了