如何将现有的Angular 2应用程序链接到Nodejs Server?

时间:2017-06-03 14:36:56

标签: javascript node.js angular

我有一个具有这种结构的Angular 2应用程序:
Structure of my Angular app

然后在服务器端: Structure of server app

我看到有两个模块依赖项文件夹,但我不知道我应该保留哪一个。

这是我的index.js文件:

  const express = require('express');
  const path = require('path');
  const http = require('http');
  const bodyParser = require('body-parser');

  // Get our API routes
  //const api = require('./server/routes/api');

  const app = express();

  // Parsers for POST data
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: false }));

  // Point static path to dist
  app.use(express.static(path.join(__dirname, 'client/portfolio')));

  // Set our api routes
  //app.use('/api', api);

  // Catch all other routes and return the index file
  app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'client/portfolio/src/index.html'));
  });

  /**
   * Get port from environment and store in Express.
   */
  const port = process.env.PORT || '3001';
  app.set('port', port);

  /**
   * Create HTTP server.
   */
  const server = http.createServer(app);

  /**
   * Listen on provided port, on all network interfaces.
   */
  server.listen(port, () => console.log(`API running on localhost:${port}`));

当我启动服务器时,我收到此消息:

  

在此处加载AppComponent内容...

但它停在这里并且不会渲染Angular应用程序。

index.html文件:

<!DOCTYPE html>
<html>
   <head>
      <title>Angular QuickStart</title>
      <base href="/">
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="styles.css">
      <link href="node_modules/@angular/material/prebuilt-themes/indigo-pink.css" rel="stylesheet">
      <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
      <!-- Polyfill(s) for older browsers -->
      <script src="node_modules/core-js/client/shim.min.js"></script>
      <script src="node_modules/hammerjs/hammer.js"></script>
      <script src="node_modules/zone.js/dist/zone.js"></script>
      <script src="node_modules/systemjs/dist/system.src.js"></script>
      <script src="systemjs.config.js"></script>
      <script>
         System.import('main.js').catch(function(err){ console.error(err); });
      </script>
   </head>
   <body>
      <my-app>Loading AppComponent content here ...</my-app>
   </body>
</html>

1 个答案:

答案 0 :(得分:0)

以下是将AngularJS与NodeJS集成的一个很好的示例[open tutorial]

诀窍就在这个块中

 <div id="about-desc">
    <p>
 Lorem ipsum dolor sit <span class="animation">amet</span>, consectetur adipisicing elit. <span class="animation"> Officia reprehenderit</span>, <span class="animation"> sit eligendi</span> deserunt, blanditiis quas porro omnis provident quidem voluptate! Fugit ipsa mollitia, atque commodi asperiores, rerum dicta ratione aut.
    </p>
 </div>

$(document).ready(function () { 
  $(".animation").addClass("animated shake");
});