如何在 node.js 服务器中提供 angular2 应用程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39845526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:36:27  来源:igfitidea点击:

How to serve an angular2 app in a node.js server

node.jsangularangular2-cli

提问by Yohan Karunanayake

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

我正在使用 Angular2 构建一个 Web 应用程序,以创建我使用 Angular2 CLI webpack 的项目。Angular2 应用程序也使用其他外部包(例如:Firebase)。除此之外,我需要创建一个在 node.js 上运行的 REST API

How can I serve both of Angular2 app and REST API using node.js server

如何使用 node.js 服务器为 Angular2 应用程序和 REST API 提供服务

回答by John Siu

  1. Use ng buildto build your app into build directory.
  2. Create nodejs app to server the build directory as static content, then create route for api.
  1. 用于ng build将您的应用程序构建到构建目录中。
  2. 创建 nodejs 应用程序以将构建目录作为静态内容提供服务,然后为 api 创建路由。

Following is an example of nodejs app using express that will serve the Angular2 app:

以下是使用 express 的 nodejs 应用程序示例,它将为 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 ...

回答by btx

None of the answers worked properly for me. And if it worked, the Angular routing did not work on reload.
So this is how I solved it. Angular routing works even on full page reload.

没有一个答案适合我。如果它有效,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);

NO angular base-href rewrite is required! Just use ng buildor ng build --prod.

不需要有角度的 base-href 重写!只需使用ng buildng build --prod

回答by NTN-JAVA

Follow the Express node server with Angular 2 CLIdocument to serve your application through Node.js server. The application is being served Through Node.js and a REST full API. You can design this REST as your requirements.

按照带有 Angular 2 CLI文档的Express 节点服务器通过 Node.js 服务器为您的应用程序提供服务。该应用程序通过 Node.js 和 REST 完整 API 提供服务。您可以根据自己的要求设计此 REST。

E.g.

例如

Serve application with http://localhost:5000/app

使用http://localhost:5000/app 为应用程序提供服务

app.get('/app/*', function(req, res) {
    res.sendFile(path.join(__dirname, 'index.html'))
});

or

或者

Serve data from REST calls with http://localhost:5000/rest/contacts

使用http://localhost:5000/rest/contacts提供来自 REST 调用的数据

app.get('/rest/user', function(req, res) {
    res.send({
        "id": 2,
        "name": "Jhon",
    })
});

回答by Amro Shafie

Based on @NTN-JAVA answer, here's a solution to serve an Angular app from NodeJS server.

基于@NTN-JAVA 的回答,这里有一个从 NodeJS 服务器提供 Angular 应用程序的解决方案。

Here's the summary from beginning:

这是从头开始的总结:

  1. npm install -g @angular/cli

  2. ng new PROJECT_NAME

  3. cd PROJECT_NAME

  4. npm install nodemon express cookie-parser body-parser morgan method-override --save

  1. npm install -g @angular/cli

  2. ng new PROJECT_NAME

  3. cd PROJECT_NAME

  4. npm install nodemon express cookie-parser body-parser morgan method-override --save

5.Create app.js:

5.创建app.js

var express = require('express');
var app = express();
var morgan = require('morgan');
var bodyParser = require('body-parser');
var port = process.env.PORT || 3000;
var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)
var router = express.Router();

console.log('——————————- Run on port '+ port);

/****************************** Router ***************************/
router.get('*', function(req, res){
    res.sendFile('index.html', { root: __dirname + '/' });
});

/****************************** /Router ***************************/

//app.use(morgan('dev')); // log every request to the console
app.use(express.static(__dirname + '/')); // Static (public) folder

app.use(bodyParser.urlencoded({extended:true}));// get information from html forms
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(methodOverride());
app.use('/', router); // app.use('/parent', router); call all from localhost:port/parent/*

app.listen(port);
  1. Edit package.jsonfile:

    { ... "scripts": { "start": "ng build; cp app.js dist/app.js; node dist/app.js", } ... }  

  2. npm start

  1. 编辑package.json文件:

    { ... "scripts": { "start": "ng build; cp app.js dist/app.js; node dist/app.js", } ... }  

  2. npm start

This answer also offers a solution for calling direct URLs from browser and resolving them correctly in your app.

此答案还提供了一种解决方案,用于从浏览器调用直接 URL 并在您的应用程序中正确解析它们。

回答by Maddy

Here is full back end code which is working

这是正在运行的完整后端代码

const express = require('express');
var app = express();
var port = 9999;

function getRoot(request, response) {
    response.sendFile(path.resolve('./public/angular/index.html'));
 }

 function getUndefined(request, response) {
     response.sendFile(path.resolve('./public/angular/index.html'));
 }


 app.use(express.static('./public/angular'));

 app.get('/', getRoot);
 app.get('/*', getUndefined);

 // Start server
 app.listen(port, function () {
    console.log('server running at port: ' + port);
});