【问题标题】:Nodejs application integrate with Angular applicationNodejs 应用程序与 Angular 应用程序集成
【发布时间】: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 它应该是useraccount 相同。现在它的工作。
  • 不错,有时候再看一遍就够了

标签: node.js angular express


【解决方案1】:

有两种可能的解决方案。

使用您的节点应用程序来提供静态前端文件。那么你就不能真正使用 ng serve (这可能是你在现场运行时会做的)。

您应该能够告诉 Express 从 Angular 构建目录中提供静态内容,如下所示:

app.use(express.static('../angular/dist')); 如果您有这样的文件结构并且使用 Node 运行 serve.js,这将起作用:

-node server
  -serve.js
-angular 
  -dist/*

您可以通过将 Angular 构建文件夹配置到您需要的任何位置来根据需要进行自定义,或者使用 Grunt/Gulp 通过构建任务将文件移动到您喜欢的文件夹中。

使用具有不同端口的 nodejs,并使用 Angular 的代理配置,让 Angular 认为 api 端口实际上是 4200(这可能是开发期间最好的)。

我认为这主要是开发过程中的一个问题,因为您很可能不会(也不应该)使用 ng serve live,所以选项 2 是我最好的建议。

要配置代理,请在 Angular 应用程序根目录中创建一个名为 proxy.config.json 的文件,其中包含以下内容:

{
  "/api/*": {
    "target": "http://localhost:3000",
    "secure": false,
    "changeOrigin": true
  }
}

然后,当您运行 ng serve 时,您可以使用 ng serve --proxy-config proxy.config.json 来运行它。

【讨论】:

    猜你喜欢
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    相关资源
    最近更新 更多