跳转到主要内容

标签(标签)

资源精选(342) Go开发(108) Go语言(103) Go(99) angular(82) LLM(75) 大语言模型(63) 人工智能(53) 前端开发(50) LangChain(43) golang(43) 机器学习(39) Go工程师(38) Go程序员(38) Go开发者(36) React(33) Go基础(29) Python(24) Vue(22) Web开发(20) Web技术(19) 精选资源(19) 深度学习(19) Java(18) ChatGTP(17) Cookie(16) android(16) 前端框架(13) JavaScript(13) Next.js(12) 安卓(11) 聊天机器人(10) typescript(10) 资料精选(10) NLP(10) 第三方Cookie(9) Redwoodjs(9) LLMOps(9) Go语言中级开发(9) 自然语言处理(9) PostgreSQL(9) 区块链(9) mlops(9) 安全(9) 全栈开发(8) ChatGPT(8) OpenAI(8) Linux(8) AI(8) GraphQL(8) iOS(8) 软件架构(7) Go语言高级开发(7) AWS(7) C++(7) 数据科学(7) whisper(6) Prisma(6) 隐私保护(6) RAG(6) JSON(6) DevOps(6) 数据可视化(6) wasm(6) 计算机视觉(6) 算法(6) Rust(6) 微服务(6) 隐私沙盒(5) FedCM(5) 语音识别(5) Angular开发(5) 快速应用开发(5) 提示工程(5) Agent(5) LLaMA(5) 低代码开发(5) Go测试(5) gorm(5) REST API(5) 推荐系统(5) WebAssembly(5) GameDev(5) CMS(5) CSS(5) machine-learning(5) 机器人(5) 游戏开发(5) Blockchain(5) Web安全(5) Kotlin(5) 低代码平台(5) 机器学习资源(5) Go资源(5) Nodejs(5) PHP(5) Swift(5) 智能体(4) devin(4) Blitz(4) javascript框架(4) Redwood(4) GDPR(4) 生成式人工智能(4) Angular16(4) Alpaca(4) 编程语言(4) SAML(4) JWT(4) JSON处理(4) Go并发(4) kafka(4) 移动开发(4) 移动应用(4) security(4) 隐私(4) spring-boot(4) 物联网(4) nextjs(4) 网络安全(4) API(4) Ruby(4) 信息安全(4) flutter(4) 专家智能体(3) Chrome(3) CHIPS(3) 3PC(3) SSE(3) 人工智能软件工程师(3) LLM Agent(3) Remix(3) Ubuntu(3) GPT4All(3) 软件开发(3) 问答系统(3) 开发工具(3) 最佳实践(3) RxJS(3) SSR(3) Node.js(3) Dolly(3) 移动应用开发(3) 低代码(3) IAM(3) Web框架(3) CORS(3) 基准测试(3) Go语言数据库开发(3) Oauth2(3) 并发(3) 主题(3) Theme(3) earth(3) nginx(3) 软件工程(3) azure(3) keycloak(3) 生产力工具(3) gpt3(3) 工作流(3) C(3) jupyter(3) 认证(3) prometheus(3) GAN(3) Spring(3) 逆向工程(3) 应用安全(3) Docker(3) Django(3) R(3) .NET(3) 大数据(3) Hacking(3) 渗透测试(3) C++资源(3) Mac(3) 微信小程序(3) Python资源(3) JHipster(3) 大型语言模型(2) 语言模型(2) 可穿戴设备(2) JDK(2) SQL(2) Apache(2) Hashicorp Vault(2) Spring Cloud Vault(2) Go语言Web开发(2) Go测试工程师(2) WebSocket(2) 容器化(2) AES(2) 加密(2) 输入验证(2) ORM(2) Fiber(2) Postgres(2) Gorilla Mux(2) Go数据库开发(2) 模块(2) 泛型(2) 指针(2) HTTP(2) PostgreSQL开发(2) Vault(2) K8s(2) Spring boot(2) R语言(2) 深度学习资源(2) 半监督学习(2) semi-supervised-learning(2) architecture(2) 普罗米修斯(2) 嵌入模型(2) productivity(2) 编码(2) Qt(2) 前端(2) Rust语言(2) NeRF(2) 神经辐射场(2) 元宇宙(2) CPP(2) 数据分析(2) spark(2) 流处理(2) Ionic(2) 人体姿势估计(2) human-pose-estimation(2) 视频处理(2) deep-learning(2) kotlin语言(2) kotlin开发(2) burp(2) Chatbot(2) npm(2) quantum(2) OCR(2) 游戏(2) game(2) 内容管理系统(2) MySQL(2) python-books(2) pentest(2) opengl(2) IDE(2) 漏洞赏金(2) Web(2) 知识图谱(2) PyTorch(2) 数据库(2) reverse-engineering(2) 数据工程(2) swift开发(2) rest(2) robotics(2) ios-animation(2) 知识蒸馏(2) 安卓开发(2) nestjs(2) solidity(2) 爬虫(2) 面试(2) 容器(2) C++精选(2) 人工智能资源(2) Machine Learning(2) 备忘单(2) 编程书籍(2) angular资源(2) 速查表(2) cheatsheets(2) SecOps(2) mlops资源(2) R资源(2) DDD(2) 架构设计模式(2) 量化(2) Hacking资源(2) 强化学习(2) flask(2) 设计(2) 性能(2) Sysadmin(2) 系统管理员(2) Java资源(2) 机器学习精选(2) android资源(2) android-UI(2) Mac资源(2) iOS资源(2) Vue资源(2) flutter资源(2) JavaScript精选(2) JavaScript资源(2) Rust开发(2) deeplearning(2) RAD(2)

This guide describes Angular Universal, a technology that renders Angular applications on the server.

A normal Angular application executes in the browser, rendering pages in the DOM in response to user actions. Angular Universal executes on the server, generating static application pages that later get bootstrapped on the client. This means that the application generally renders more quickly, giving users a chance to view the application layout before it becomes fully interactive.

For a more detailed look at different techniques and concepts surrounding SSR, check out this article.

Easily prepare an application for server-side rendering using the Angular CLI. The CLI schematic @nguniversal/express-engine performs the required steps, as described.

Angular Universal requires an active LTS or maintenance LTS version of Node.js. See the engines property in the package.json file to learn about the currently supported versions.

NOTE:
Download the finished sample code, which runs in a Node.js® Express server.

Universal tutorial

The Tour of Heroes tutorial is the foundation for this walkthrough.

In this example, the Angular CLI compiles and bundles the Universal version of the application with the Ahead-of-Time (AOT) compiler. A Node.js Express web server compiles HTML pages with Universal based on client requests.

To create the server-side application module, app.server.module.ts, run the following CLI command.

ng add @nguniversal/express-engine

The command creates the following folder structure.

src

index.html                             // <-- app web page

main.ts                                  // <-- bootstrapper for client app

main.server.ts                       // <-- * bootstrapper for server app

style.css                                // <-- styles for the app

app/  …                                   // <-- application code

app.server.module.ts     // <-- * server-side application module

server.ts                                // <-- * express web server

tsconfig.json                        // <-- TypeScript base configuration

tsconfig.app.json                // <-- TypeScript browser application configuration

tsconfig.server.json            // <-- TypeScript server application configuration

tsconfig.spec.json              // <-- TypeScript tests configuration

The files marked with * are new and not in the original tutorial sample.

Universal in action

To start rendering your application with Universal on your local system, use the following command.

npm run dev:ssr

Open a browser and navigate to http://localhost:4200. You should see the familiar Tour of Heroes dashboard page.

Navigation using routerLinks works correctly because they use the built-in anchor (<a>) elements. You can go from the Dashboard to the Heroes page and back. Click a hero on the Dashboard page to display its Details page.

If you throttle your network speed so that the client-side scripts take longer to download (instructions following), you'll notice:

  • You can't add or delete a hero
  • The search box on the Dashboard page is ignored
  • The Back and Save buttons on the Details page don't work

The transition from the server-rendered application to the client application happens quickly on a development machine, but you should always test your applications in real-world scenarios.

You can simulate a slower network to see the transition more clearly as follows:

  1. Open the Chrome Dev Tools and go to the Network tab.
  2. Find the Network Throttling dropdown on the far right of the menu bar.
  3. Try one of the "3G" speeds.

The server-rendered application still launches quickly but the full client application might take seconds to load.

Why use server-side rendering?

There are three main reasons to create a Universal version of your application.

Facilitate web crawlers (SEO)

Google, Bing, Facebook, Twitter, and other social media sites rely on web crawlers to index your application content and make that content searchable on the web. These web crawlers might be unable to navigate and index your highly interactive Angular application as a human user could do.

Angular Universal can generate a static version of your application that is easily searchable, linkable, and navigable without JavaScript. Universal also makes a site preview available because each URL returns a fully rendered page.

Improve performance on mobile and low-powered devices

Some devices don't support JavaScript or execute JavaScript so poorly that the user experience is unacceptable. For these cases, you might require a server-rendered, no-JavaScript version of the application. This version, however limited, might be the only practical alternative for people who otherwise couldn't use the application at all.

Show the first page quickly

Displaying the first page quickly can be critical for user engagement. Pages that load faster perform better, even with changes as small as 100ms. Your application might have to launch faster to engage these users before they decide to do something else.

With Angular Universal, you can generate landing pages for the application that look like the complete application. The pages are pure HTML, and can display even if JavaScript is disabled. The pages don't handle browser events, but they do support navigation through the site using routerLink.

In practice, you'll serve a static version of the landing page to hold the user's attention. At the same time, you'll load the full Angular application behind it. The user perceives near-instant performance from the landing page and gets the full interactive experience after the full application loads.

Universal web servers

A Universal web server responds to application page requests with static HTML rendered by the Universal template engine. The server receives and responds to HTTP requests from clients (usually browsers), and serves static assets such as scripts, CSS, and images. It might respond to data requests, either directly or as a proxy to a separate data server.

The sample web server for this guide is based on the popular Express framework.

NOTE:
Any web server technology can serve a Universal application as long as it can call Universal's renderModule() function. The principles and decision points discussed here apply to any web server technology.

Universal applications use the Angular platform-server package (as opposed to platform-browser), which provides server implementations of the DOM, XMLHttpRequest, and other low-level features that don't rely on a browser.

The server (Node.js Express in this guide's example) passes client requests for application pages to the NgUniversal ngExpressEngine. Under the hood, this calls Universal's renderModule() function, while providing caching and other helpful utilities.

The renderModule() function takes as inputs a template HTML page (usually index.html), an Angular module containing components, and a route that determines which components to display. The route comes from the client's request to the server.

Each request results in the appropriate view for the requested route. The renderModule() function renders the view within the <app> tag of the template, creating a finished HTML page for the client.

Finally, the server returns the rendered page to the client.

Working around the browser APIs

Because a Universal application doesn't execute in the browser, some of the browser APIs and capabilities might be missing on the server.

For example, server-side applications can't reference browser-only global objects such as windowdocumentnavigator, or location.

Angular provides some injectable abstractions over these objects, such as Location or DOCUMENT; it might substitute adequately for these APIs. If Angular doesn't provide it, it's possible to write new abstractions that delegate to the browser APIs while in the browser and to an alternative implementation while on the server (also known as shimming).

Similarly, without mouse or keyboard events, a server-side application can't rely on a user clicking a button to show a component. The application must determine what to render based solely on the incoming client request. This is a good argument for making the application routable.

Universal template engine

The important bit in the server.ts file is the ngExpressEngine() function.

server.ts
// Our Universal express-engine (found @ https://github.com/angular/universal/tree/main/modules/express-engine)
server.engine('html', ngExpressEngine({
  bootstrap: AppServerModule,
}));

The ngExpressEngine() function is a wrapper around Universal's renderModule() function which turns a client's requests into server-rendered HTML pages. It accepts an object with the following properties:

PROPERTIES DETAILS
bootstrap The root NgModule or NgModule factory to use for bootstrapping the application when rendering on the server. For the example application, it is AppServerModule. It's the bridge between the Universal server-side renderer and the Angular application.
extraProviders This property is optional and lets you specify dependency providers that apply only when rendering the application on the server. Do this when your application needs information that can only be determined by the currently running server instance.

The ngExpressEngine() function returns a Promise callback that resolves to the rendered page. It's up to the engine to decide what to do with that page. This engine's Promise callback returns the rendered page to the web server, which then forwards it to the client in the HTTP response.

NOTE:
These wrappers help hide the complexity of the renderModule() function. There are more wrappers for different backend technologies at the Universal repository.

Filtering request URLs

NOTE:
The basic behavior described below is handled automatically when using the NgUniversal Express schematic. This is helpful when trying to understand the underlying behavior or replicate it without using the schematic.

The web server must distinguish app page requests from other kinds of requests.

It's not as simple as intercepting a request to the root address /. The browser could ask for one of the application routes such as /dashboard/heroes, or /detail:12. In fact, if the application were only rendered by the server, every application link clicked would arrive at the server as a navigation URL intended for the router.

Fortunately, application routes have something in common: their URLs lack file extensions. (Data requests also lack extensions but they can be recognized because they always begin with /api.) All static asset requests have a file extension (such as main.js or /node_modules/zone.js/bundles/zone.umd.js).

Because you use routing, you can recognize the three types of requests and handle them differently.

ROUTING REQUEST TYPES DETAILS
Data request Request URL that begins /api.
App navigation Request URL with no file extension.
Static asset All other requests.

A Node.js Express server is a pipeline of middleware that filters and processes requests one after the other. You configure the Node.js Express server pipeline with calls to server.get() like this one for data requests.

server.ts (data URL)
// TODO: implement data requests securely
server.get('/api/**', (req, res) => {
  res.status(404).send('data requests are not yet supported');
});

NOTE:
This sample server doesn't handle data requests.

The tutorial's "in-memory web API" module, a demo and development tool, intercepts all HTTP calls and simulates the behavior of a remote data server. In practice, you would remove that module and register your web API middleware on the server here.

The following code filters for request URLs with no extensions and treats them as navigation requests.

server.ts (navigation)
// All regular routes use the Universal engine
server.get('*', (req, res) => {
  res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
});

Serving static files safely

A single server.use() treats all other URLs as requests for static assets such as JavaScript, image, and style files.

To ensure that clients can only download the files that they are permitted to see, put all client-facing asset files in the /dist folder and only honor requests for files from the /dist folder.

The following Node.js Express code routes all remaining requests to /dist, and returns a 404 - NOT FOUND error if the file isn't found.

server.ts (static files)
// Serve static files from /browser
server.get('*.*', express.static(distFolder, {
  maxAge: '1y'
}));

Using absolute URLs for HTTP (data) requests on the server

The tutorial's HeroService and HeroSearchService delegate to the Angular HttpClient module to fetch application data. These services send requests to relative URLs such as api/heroes. In a server-side rendered app, HTTP URLs must be absolute (for example, https://my-server.com/api/heroes). This means that the URLs must be somehow converted to absolute when running on the server and be left relative when running in the browser.

If you are using one of the @nguniversal/*-engine packages (such as @nguniversal/express-engine), this is taken care for you automatically. You don't need to do anything to make relative URLs work on the server.

If, for some reason, you are not using an @nguniversal/*-engine package, you might need to handle it yourself.

The recommended solution is to pass the full request URL to the options argument of renderModule() or renderModuleFactory() (depending on what you use to render AppServerModule on the server). This option is the least intrusive as it does not require any changes to the application. Here, "request URL" refers to the URL of the request as a response to which the application is being rendered on the server. For example, if the client requested https://my-server.com/dashboard and you are rendering the application on the server to respond to that request, options.url should be set to https://my-server.com/dashboard.

Now, on every HTTP request made as part of rendering the application on the server, Angular can correctly resolve the request URL to an absolute URL, using the provided options.url.

Useful scripts

SCRIPTS DETAILS
npm run dev:ssr
Similar to ng serve, which offers live reload during development, but uses server-side rendering. The application runs in watch mode and refreshes the browser after every change. This command is slower than the actual ng serve command.
ng build && ng run app-name:server
Builds both the server script and the application in production mode. Use this command when you want to build the project for deployment.
npm run serve:ssr
Starts the server script for serving the application locally with server-side rendering. It uses the build artifacts created by ng run build:ssr, so make sure you have run that command as well.

NOTE:
serve:ssr is not intended to be used to serve your application in production, but only for testing the server-side rendered application locally.

npm run prerender
Used to prerender an application's pages. Read more about prerendering here.

标签