Yoh*_*ake 8 node.js angular2-cli angular
我正在使用Angular2构建一个Web应用程序,以创建我正在使用Angular2 CLI webpack的项目.Angular2应用程序也使用其他外部程序包(例如:Firebase).除此之外,我还需要创建一个在node.js上运行的REST API
如何使用node.js服务器同时提供Angular2应用程序和REST API
ng build将您的应用程序构建到构建目录中.以下是使用express的nodejs app的示例,它将为Angular2应用程序提供服务:
/*
Put content of angular2 build into 'public' folder.
*/
const html = __dirname + '/public';
const port = 4000;
const apiUrl = '/api';
// Express
const bodyParser = require('body-parser');
const compression = require('compression');
const express = require('express');
var app = express();
app
.use(compression())
.use(bodyParser.json())
// Static content
.use(express.static(html))
// Default route
.use(function(req, res) {
res.sendFile(html + 'index.html');
})
// Start server
.listen(port, function () {
console.log('Port: ' + port);
console.log('Html: ' + html);
});
// continue with api code below ...
Run Code Online (Sandbox Code Playgroud)
没有一个答案适合我。如果它有效,Angular 路由在重新加载时不起作用。
所以这就是我解决它的方法。Angular 路由甚至在整页重新加载时也能工作。
function getRoot(request, response) {
response.sendFile(path.resolve('./public/angular/index.html'));
}
function getUndefined(request, response) {
response.sendFile(path.resolve('./public/angular/index.html'));
}
// Note the dot at the beginning of the path
app.use(express.static('./public/angular'));
app.get('/', getRoot);
app.get('/*', getUndefined);
Run Code Online (Sandbox Code Playgroud)
不需要有角度的 base-href 重写!只需使用
ng build或ng build --prod。