Skip to content

按需渲染

你的 Astro 项目代码必须渲染为 HTML 才能显示在网络上。

¥Your Astro project code must be rendered to HTML in order to be displayed on the web.

默认情况下,Astro 页面、路由和 API 端点将在构建时作为静态页面预渲染。但是,你可以选择在请求路由时由服务器按需渲染部分或全部路由。

¥By default, Astro pages, routes, and API endpoints will be pre-rendered at build time as static pages. However, you can choose to render some or all of your routes on demand by a server when a route is requested.

每次访问都会生成按需渲染的页面和路由,并且可以为每个查看者进行自定义。例如,按需渲染的页面可以向登录用户显示其账户信息或显示最新更新的数据,而无需重建整个站点。

¥On-demand rendered pages and routes are generated per visit, and can be customized for each viewer. For example, a page rendered on demand can show a logged-in user their account information or display freshly updated data without requiring a full-site rebuild.

在请求时在服务器上按需渲染也称为服务器端渲染 (SSR)。

¥On-demand rendering on the server at request time is also known as server-side rendering (SSR).

¥Server adapters

要按需渲染任何页面,你需要添加一个适配器。每个适配器都允许 Astro 输出在特定运行时运行项目的脚本:在服务器上运行代码以在请求时生成页面的环境(例如 Netlify、Cloudflare)。

¥To render any page on demand, you need to add an adapter. Each adapter allows Astro to output a script that runs your project on a specific runtime: the environment that runs code on the server to generate pages when they are requested (e.g. Netlify, Cloudflare).

即使你的网站完全是静态的并且你没有按需渲染任何页面,你可能还希望添加适配器。例如,Netlify 适配器 启用 Netlify 的图片 CDN,而 服务器岛 需要安装适配器才能在组件上使用 server:defer

¥You may also wish to add an adapter even if your site is entirely static and you are not rendering any pages on demand. For example, the Netlify adapter enables Netlify’s Image CDN, and server islands require an adapter installed to use server:defer on a component.

SSR 适配器

Astro 维护 Node.jsNetlifyVercelCloudflare 的官方适配器。你可以找到 我们的集成目录中的官方和社区适配器。选择与你的 部署环境 相对应的一个。

¥Astro maintains official adapters for Node.js, Netlify, Vercel, and Cloudflare. You can find both official and community adapters in our integrations directory. Choose the one that corresponds to your deployment environment.

¥Add an Adapter

你可以使用以下 astro add 命令添加任何 Astro 维护的官方适配器集成。这将一步安装适配器并对 astro.config.mjs 文件进行适当的更改。

¥You can add any of the official adapter integrations maintained by Astro with the following astro add command. This will install the adapter and make the appropriate changes to your astro.config.mjs file in one step.

例如,要安装 Netlify 适配器,请运行:

¥For example, to install the Netlify adapter, run:

终端窗口
npx astro add netlify

你也可以自己 通过安装 NPM 包手动添加适配器(例如 @astrojs/netlify)并更新 astro.config.mjs

¥You can also add an adapter manually by installing the NPM package (e.g. @astrojs/netlify) and updating astro.config.mjs yourself.

请注意,不同的适配器可能具有不同的配置设置。阅读每个适配器的文档,并将任何必要的配置选项应用于 astro.config.mjs 中你选择的适配器

¥Note that different adapters may have different configuration settings. Read each adapter’s documentation, and apply any necessary config options to your chosen adapter in astro.config.mjs

¥Enabling on-demand rendering

默认情况下,你的整个 Astro 站点将被预渲染,并且静态 HTML 页面将发送到浏览器。但是,你可以选择不预渲染任何需要服务器渲染的路由,例如,检查 cookie 并显示个性化内容的页面。

¥By default, your entire Astro site will be prerendered, and static HTML pages will be sent to the browser. However, you may opt out of prerendering on any routes that require server rendering, for example, a page that checks for cookies and displays personalized content.

首先,添加适配器集成 用于你的服务器运行时,以便在 Astro 项目中启用按需服务器渲染。

¥First, add an adapter integration for your server runtime to enable on-demand server rendering in your Astro project.

然后,在你想要按需渲染的单个页面或端点的顶部添加 export const prerender = false。你网站的其余部分将保持静态网站:

¥Then, add export const prerender = false at the top of the individual page or endpoint you want to render on demand. The rest of your site will remain a static site:

src/pages/page-rendered-on-demand.astro
---
export const prerender = false
---
<html>
<!--
This content will be server-rendered on demand!
Just add an adapter integration for a server runtime!
All other pages are statically-generated at build time!
-->
<html>

以下示例显示选择退出预渲染,以便在每次点击端点时显示随机数:

¥The following example shows opting out of prerendering in order to display a random number each time the endpoint is hit:

src/pages/randomnumber.js
export const prerender = false;
export async function GET() {
let number = Math.random();
return new Response(
JSON.stringify({
number,
message: `Here's a random number: ${number}`,
}),
);
}

¥'server' mode

对于高度动态的应用,添加适配器后,你可以默认 将你的构建输出配置设置为 output: 'server' 以服务器渲染所有页面。这相当于选择退出每个页面的预渲染。

¥For a highly dynamic app, after adding an adapter, you can set your build output configuration to output: 'server' to server-render all your pages by default. This is the equivalent of opting out of prerendering on every page.

然后,如果需要,你可以选择预渲染任何不需要服务器执行的单个页面,例如隐私政策或关于页面。

¥Then, if needed, you can choose to prerender any individual pages that do not require a server to execute, such as a privacy policy or about page.

src/pages/about-my-app.astro
---
export const prerender = true
---
<html>
<!--
`output: 'server'` is configured, but this page is static!
The rest of my site is rendered on demand!
-->
<html>

export const prerender = true 添加到任何页面或路由以预渲染静态页面或端点:

¥Add export const prerender = true to any page or route to prerender a static page or endpoint:

src/pages/myendpoint.js
export const prerender = true;
export async function GET() {
return new Response(
JSON.stringify({
message: `This is my static endpoint`,
}),
);
}
See more about the output setting in the configuration reference.

¥On-demand rendering features

¥HTML streaming

通过 HTML 流,文档被分成多个块,按顺序通过网络发送,并按该顺序渲染在页面上。Astro 在按需渲染中使用 HTML 流,在渲染每个组件时将其发送到浏览器。这可以确保用户尽快看到你的 HTML,尽管网络条件可能会导致大型文档下载缓慢,并且等待数据获取可能会阻止页面渲染。

¥With HTML streaming, a document is broken up into chunks, sent over the network in order, and rendered on the page in that order. Astro uses HTML streaming in on-demand rendering to send each component to the browser as it renders them. This makes sure the user sees your HTML as fast as possible, although network conditions can cause large documents to be downloaded slowly, and waiting for data fetches can block page rendering.

按需渲染的页面或 API 端点可以检查、设置、获取和删除 cookie。

¥A page or API endpoint rendered on demand can check, set, get, and delete cookies.

下面的示例更新页面查看计数器的 cookie 值:

¥The example below updates the value of a cookie for a page view counter:

src/pages/index.astro
---
export const prerender = false; // Not needed in 'server' mode
let counter = 0
if (Astro.cookies.has('counter')) {
const cookie = Astro.cookies.get('counter')
const value = cookie?.number()
if (value !== undefined && !isNaN(value)) counter = value + 1
}
Astro.cookies.set('counter', String(counter))
---
<html>
<h1>Counter = {counter}</h1>
</html>

请参阅 API 参考中有关 Astro.cookies and the AstroCookie type 的更多详细信息。

¥See more details about Astro.cookies and the AstroCookie type in the API reference.

Astro.response 是标准 ResponseInit 对象。它可用于设置响应状态和标头。

¥Astro.response is a standard ResponseInit object. It can be used to set the response status and headers.

以下示例在产品不存在时为产品页面设置响应状态和状态文本:

¥The example below sets a response status and status text for a product page when the product does not exist:

src/pages/product/[id].astro
---
export const prerender = false; // Not needed in 'server' mode
import { getProduct } from '../api';
const product = await getProduct(Astro.params.id);
// No product found
if (!product) {
Astro.response.status = 404;
Astro.response.statusText = 'Not found';
}
---
<html>
<!-- Page here... -->
</html>

你可以使用 Astro.response.headers 对象设置标题:

¥You can set headers using the Astro.response.headers object:

src/pages/index.astro
---
export const prerender = false; // Not needed in 'server' mode
Astro.response.headers.set('Cache-Control', 'public, max-age=3600');
---
<html>
<!-- Page here... -->
</html>

¥Return a Response object

你还可以使用按需渲染从任何页面直接返回 响应 对象,手动或使用 Astro.redirect

¥You can also return a Response object directly from any page using on-demand rendering either manually or with Astro.redirect.

以下示例在动态页面上的数据库中查找 ID,如果产品不存在,则返回 404,如果产品不再可用,则将用户重定向到另一个页面,或者显示产品:

¥The example below looks up an ID in the database on a dynamic page and either it returns a 404 if the product does not exist, or it redirects the user to another page if the product is no longer available, or it displays the product:

src/pages/product/[id].astro
---
export const prerender = false; // Not needed in 'server' mode
import { getProduct } from '../api';
const product = await getProduct(Astro.params.id);
// No product found
if (!product) {
return new Response(null, {
status: 404,
statusText: 'Not found'
});
}
// The product is no longer available
if (!product.isAvailable) {
return Astro.redirect("/products", 301);
}
---
<html>
<!-- Page here... -->
</html>

Astro.request 是标准 要求 对象。它可用于获取 urlheadersmethod,甚至请求的主体。

¥Astro.request is a standard Request object. It can be used to get the url, headers, method, and even the body of the request.

你可以从此对象访问非静态生成的页面的其他信息。

¥You can access additional information from this object for pages that are not statically generated.

请求的标头在 Astro.request.headers 上可用。这与浏览器的 Request.headers 类似。它是一个 标头 对象,你可以在其中检索 cookie 等标头。

¥The headers for the request are available on Astro.request.headers. This works like the browser’s Request.headers. It is a Headers object where you can retrieve headers such as the cookie.

src/pages/index.astro
---
export const prerender = false; // Not needed in 'server' mode
const cookie = Astro.request.headers.get('cookie');
// ...
---
<html>
<!-- Page here... -->
</html>

请求中使用的 HTTP 方法可用为 Astro.request.method。这与浏览器的 Request.method 类似。它返回请求中使用的 HTTP 方法的字符串表示形式。

¥The HTTP method used in the request is available as Astro.request.method. This works like the browser’s Request.method. It returns the string representation of the HTTP method used in the request.

src/pages/index.astro
---
export const prerender = false; // Not needed in 'server' mode
console.log(Astro.request.method) // GET (when navigated to in the browser)
---

请参阅 API 参考中有关 Astro.request 的更多详细信息。

¥See more details about Astro.request in the API reference.

¥Server Endpoints

服务器端点(也称为 API 路由)是从 src/pages/ 文件夹中的 .js.ts 文件导出的特殊函数。API 路由是服务器端按需渲染的强大功能,能够在服务器上安全地执行代码。

¥A server endpoint, also known as an API route, is a special function exported from a .js or .ts file within the src/pages/ folder. A powerful feature of server-side rendering on demand, API routes are able to securely execute code on the server.

该函数接受 端点上下文 并返回 响应

¥The function takes an endpoint context and returns a Response.

要了解更多信息,请参阅我们的 端点指南

¥To learn more, see our Endpoints Guide.

Astro 中文网 - 粤ICP备13048890号