首页 文章

Nodejs应用程序与Angular应用程序集成

提问于
浏览
0

Nodejs应用程序使用Express(express genrator)创建,并使用把手作为视图引擎 . 创建了几条路线,工作正常 . 应用程序在端口3000上运行 .

快递路线:

...
app.use('/', index);
app.use('/landing', landing);
app.use('/home', home);
app.use('/api', api);
...

在Angular上构建了一个管理面板单独的应用程序

目前Angular应用程序在端口4200上运行,并使用在端口3000上运行的NodeJs应用程序中的API .

角度应用路线

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

What I'm trying: 想要在同一端口(即端口3000)上运行NodeJ和Angular应用程序 .

What I have done: 编译并将index.html文件放在nodejs文件夹结构的/ views / ngapp /中 .

在nodejs中创建一个“用户”路由并提供角度应用程序的index.html文件 . (可能这不是一个好方法)

app.get('/user', function (req, res, next) {
  res.sendFile(path.join(__dirname + '/views/ngapp/index.html'));
});

不知怎的,它已加载但遇到错误:
enter image description here

我的问题是我们如何将Nodeular应用程序(可能在不同的路径上运行,但在相同的端口上运行)与NodeJs应用程序集成,NodeJs应用程序已经定义了一些路由并使用视图引擎来呈现页面 .

1 回答

  • 0

    有两种可能的解决方案 .

    使用节点应用程序提供静态前端文件 . 然后你不能真正使用ng服务(这可能是你在现场直播时所做的) .

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

    app.use(express.static( '../角/ DIST'));如果您有这样的文件结构并且正在使用Node运行serve.js,哪个会工作:

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

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

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

    这主要是我在开发过程中的一个问题,因为你很可能不会(也不应该)使用ng live live,所以选项2将是我最好的推荐 .

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

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

    然后,当您运行服务时,使用ng serve --proxy-config proxy.config.json运行它 .

相关问题