如何将我的angular2模板链接到节点js表示后端

时间:2017-04-09 14:27:49

标签: node.js angular express

我尝试将后端(NodeJS,Express)与前端(Angular 2)连接,但我不知道如何启动。任何人都可以帮助我如何将后端与前端链接,如果有配置或我必须实现的代码。

1 个答案:

答案 0 :(得分:0)

使用Angular CLI项目。 做 ng build --prod --base-href。生成dist文件夹。

现在通过节点JS提供此文件夹 下面是片段,它将为dist fodler提供服务。

// Get dependencies
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, 'dist')));

// 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, 'dist/index.html'));
});

/**
 * Get port from environment and store in Express.
 */
const port = process.env.PORT || '3000';
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}`))