如何在生产服务器上部署带有服务器端渲染的Angular 4应用程序

14
我已经寻找了约3个小时,以在启用“服务器端渲染”的服务器上托管一个Angular 4应用程序。需要注意的是-我有一个安装了Apache(Ubuntu)的AWS服务器。
首先,我已经知道如何托管没有服务器端渲染的Angular 4应用程序。但我的主要担忧是我想启用服务器端渲染。
在本地,我使用“npm start”命令,它会自动在“http://localhost:4000”上为应用程序提供服务(启用服务器端渲染)。
我的“package.json”文件长这样:
...
"scripts": {
    "serve": "ng serve",
    "prestart": "ng build --prod && ngc && webpack",
    "start": "node dist/server.js",
    "build": "ng build"
},
...

这些命令都正常运行。但我很困惑,是否应该再次运行?

npm start

在生产服务器上,安装应用还需要node_modules, 这对我来说似乎不是正确的方法?

有人能帮我启用“服务器端渲染”来托管我的应用程序吗?


很奇怪,下面的回答者甚至没有认真阅读你的问题到最后。我刚刚部署了我的Angular SSR并通过Nginx代理,但一些静态文件无法显示,出现了问题。 - KhoPhi
@Rexford,没错...我很震惊没有人认真读我的问题,他们回答自己喜欢的内容...其实我也和你一样做了,只不过我使用的是Apache。 - Saumya Rastogi
我在下面分享了如何在生产环境中运行我的SSR Angular应用程序。希望能对你有所帮助。 - KhoPhi
我还写了一篇关于如何使用Angular 4实现服务器端渲染的文章 - https://blog.squareboat.com/how-to-implement-server-side-rendering-using-angular-4-5da10f4dcb61 - Saumya Rastogi
@Saumya Rastogi 请问在 Sentora 服务器上部署 Angular 项目是否可行?麻烦告诉我,我需要知道。 - vidy
4个回答

6
有人能帮我启用"服务器端渲染"来托管我的应用吗?
是的,但很遗憾我使用 Nginx。然而,在 Apache 或其他什么地方采用的方法都不应该有任何不同。
以下是我如何在生产中托管我的服务器端渲染 Angular 应用程序(我在 DO 上)。我写了一篇关于它的文章(链接)
在构建好你的 SSR 之后,你应该会得到类似这样的东西: enter image description here 当你成功将 dist/ 文件夹内的所有文件都传输至远程服务器时,你需要使用 pm2(我用它来运行我的 node.js 应用程序)来运行它。
运行pm2 start path/to/dist/server.js --name name_of_process 应用将在 localhost:4000 上运行。
下面的 Nginx 虚拟服务器块应该将所有请求代理到你的 Nginx,并转发到服务器端渲染的 Angular 应用程序。
实际上,下面的 nginx 配置文件既为您的 angular SSR 提供静态内容,也为非静态文件请求提供代理。
upstream ssr_khophi_nodejs {
    server 127.0.0.1:4000;
}

server {
    listen 443 ssl http2;

    server_name staging.khophi.com; # <--- Change this part

    include /etc/nginx/ssl/ssl-params.conf;# <--- Ignore this part if not using SSL
    include /etc/nginx/ssl/khophi.com.ssl;# <--- Ignore this part if not using SSL

    root /home/khophi/khophi.com/ssr/dist/browser; # <-- Notice where we're point to

   location / {
        try_files $uri $uri @backend; # <--- This looks for requests (statics i.e js/css/fonts)
                                      # in /ssr/dist/browser folder. If nothing found, calls @backend
    }

    location @backend {
        # NOTE THERE IS NO TRAILING SLASH AT THE END. NO TRAILING SLASH. NO SLASH. NO!
        proxy_pass http://ssr_khophi_nodejs; # <--- THIS DOES NOT HAVE A TRAILING '/'
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_http_version 1.1;
        proxy_set_header X-NginX-Proxy true;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_cache_bypass $http_upgrade;
        proxy_redirect off;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

server {
    listen 80;
    server_name staging.khophi.com;
    return 301 https://$server_name$request_uri?;
}

希望这能帮到您。


谢谢您的回答,但我必须在Apache上实现这个。我已经想出了如何准备服务器端渲染的方法。我还在Medium上写了一篇文章 - https://blog.squareboat.com/how-to-implement-server-side-rendering-using-angular-4-5da10f4dcb61 - Saumya Rastogi
@SaumyaRastogi,你的博客主要是关于服务器端渲染实现的。我没找到你如何在服务器上部署它? - Vivek Sinha
客户/终端用户不会在服务器终端上输入“pm2 start path/to/dist/server.js --name name_of_process”。客户如何通过输入URL加载应用程序页面? - Sunil Kumar
如果我理解正确,您想要在不使用终端的情况下运行 pm2 start path/to/dist/server.js --name name_of_process 吗?如果是这样,我不知道还有其他方法可以通过 URL 运行您的应用程序。 - KhoPhi
@KhoPhi 请问在Sentora服务器上部署Angular项目是否可行?麻烦告诉我,我需要知道。 - vidy
如何更改端口而不是默认运行在4000端口?我尝试使用pm2 start path/to/dist/server.js --name name_of_process --port 4001 / pm2 start path/to/dist/server.js --name name_of_process -- --port 4001,但这并没有起作用。 - jamuna

-3

好的,抱歉我误读了你的问题 :)

首先,Apache不再需要为您的应用程序提供服务。这是因为node.js将为您提供服务。

因此,如果您的服务器上不需要apache服务,出于安全考虑和避免应用程序之间的端口冲突,您应该禁用它。

服务器渲染需要修改您的angular应用程序。让我们开始吧。

1)进入您的angular项目并安装以下软件包:

npm i -S @angular/platform-server @angular/animations express

2) 打开 src/app/app.module.ts 文件,并修改下面的注释行,将其替换为您的应用程序名称。
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule.withServerTransition({ appId: 'your-angular-app-name' }), // You just have to change this line
    FormsModule,
    HttpModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

3) 现在,我们将在您的应用程序中设置服务器。为此,请创建文件app/src/app.server.module.ts并添加以下代码。

import { NgModule } from '@angular/core';
import { ServerModule } from '@angular/platform-server';
import { AppModule } from './app.module';
import { AppComponent } from './app.component';

@NgModule({
imports: [
    ServerModule, // Load the servermodule
    AppModule     // Load the modules of AppModule
],
bootstrap: [AppComponent]
})
export class AppServerModule { }

4) 创建文件src/server.ts并添加以下代码。这是Node服务器。

import 'reflect-metadata';
import 'zone.js/dist/zone-node';
import { platformServer, renderModuleFactory } from '@angular/platform-server';
import { enableProdMode } from '@angular/core';
import { AppServerModuleNgFactory } from '../dist/ngfactory/src/app/app.server.module.ngfactory';
import * as express from 'express';
import { readFileSync } from 'fs';
import { join } from 'path';
const PORT = 4000;
enableProdMode();
const app = express();
let template = readFileSync(join(__dirname, '..', 'dist', 'index.html')).toString();
app.engine('html', (_, options, callback) => {
  const opts = { document: template, url: options.req.url };
  renderModuleFactory(AppServerModuleNgFactory, opts)
    .then(html => callback(null, html));
});
app.set('view engine', 'html');
app.set('views', 'src');
app.get('*.*', express.static(join(__dirname, '..', 'dist')));
app.get('*', (req, res) => {
  res.render('index', { req });
});
app.listen(PORT, () => {
  console.log(`Listening on http://localhost:${PORT}...`);
});

5) 打开 src/tsconfig.app.json 并将文件 server.ts 添加到 exclude json 变量中。

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "module": "es2015",
    "baseUrl": "",
    "types": []
  },
  "exclude": [
    "server.ts", # Just here !
    "test.ts",
    "**/*.spec.ts"
  ]
}

6) 打开位于项目根目录下的tsconfig.json文件,并添加以下angularCompilerOptions选项:

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "src",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2016",
      "dom"
    ]
  },
  "angularCompilerOptions": { 
    "genDir": "./dist/ngfactory",
    "entryModule": "./src/app/app.module#AppModule"
  }  
}

7) 现在,修改你的package.json文件,让你的编程变得更加轻松。

{
  "scripts": {
    "prestart": "ng build --prod && ngc",
    "start": "ts-node src/server.ts", 
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
}

8) 现在你可以使用以下方式测试你的应用程序:

npm start

希望这能对您有所帮助。

注意: 如果您的项目已经存在,那么您可能会遇到一些模块问题,例如 Angular Material,因为 node.js 不知道 window 对象、document 对象。

因此,您需要:

  • 创建app.common.module.ts,其他模块加载文件将继承它,并收集公共模块(客户端+服务器)。

  • 最后将让我们困扰的模块放在app.module.ts中。

Cdly。


1
抱歉,我认为这并没有回答我的问题。我不是在问如何构建项目。你上面说的方式和我实现的方式一样,但我的问题是 - 如何在服务器上提供特定的应用程序?我想要的是实现方法! - Saumya Rastogi

-5

no 7 package.jsno script has duplicate start script.

此外,我们需要服务器支持,这在共享托管帐户中不包括。


-6

实际上这很简单。

使用 shell 进入你的 Angular 4 项目目录,然后执行以下命令:

$ ng build --prod

这将编译应用程序,结果位于您的Angular应用程序根目录下的dist文件夹中。

现在,您只需将dist文件夹的内容放入HTTP服务器中并享受爆米花即可。

敬礼, Jerry Yong-busson。


2
我认为你并没有仔细阅读我的问题。你提供的解决方案,正如我在问题中所提到的那样,我已经知道了。我想要的是启用服务器端渲染的应用程序托管解决方案... - Saumya Rastogi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接