我有一个具有以下结构的 Angular 2 应用程序:
Structure of my Angular app
然后在服务器端: Structure of server app
我看到有 2 个模块依赖项文件夹,但我不知道应该保留哪一个。
这是我的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}`));
当我启动服务器时,我收到此消息:
Loading AppComponent content here ...
但它停在这里并且不会渲染 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>
最佳答案
这是将 AngularJS 与 NodeJS 集成的一个很好的示例 [ open tutorial ]
诀窍就在这个 block
/* GET home page. */
router.get('/', function(req, res, next) {
res.sendFile(path.join(__dirname, '../', 'views', 'index.html'));
});
关于javascript - 如何将现有的 Angular 2 应用程序链接到 Nodejs 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44345039/