如何在Node.js服务器中服务angular2应用 [英] How to serve an angular2 app in a node.js server
本文介绍了如何在Node.js服务器中服务angular2应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Angular2构建一个Web应用程序,以创建我正在使用Angular2 CLI Webpack的项目. Angular2应用程序还使用其他外部软件包(例如:Firebase).除此之外,我需要创建一个在node.js上运行的REST API
I'm building a web app using Angular2, to create the project I'm using Angular2 CLI webpack. Angular2 app uses other external packages also (Eg: Firebase). In addition to that, I need to create a REST API running on node.js
如何使用node.js服务器同时提供Angular2应用和REST API
How can I serve both of Angular2 app and REST API using node.js server
推荐答案
- 使用
ng build
将您的应用程序构建到构建目录中. - 创建nodejs应用程序以将构建目录作为静态内容提供服务器,然后为api创建路由.
- Use
ng build
to build your app into build directory. - Create nodejs app to server the build directory as static content, then create route for api.
以下是一个使用express的nodejs应用示例,它将为Angular2应用提供服务:
Following is an example of nodejs app using express that will serve the Angular2 app:
/*
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 ...
这篇关于如何在Node.js服务器中服务angular2应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文