Skip to content

按需渲染适配器

Astro 允许你为部分或全部页面和端点选择按需渲染。这也称为服务器端渲染 (SSR):当请求时在服务器上生成 HTML 页面并将其发送到客户端。一个适配器用于在服务器上运行你的项目并处理这些请求。

¥Astro allows you to choose on-demand rendering for some, or all of your pages and endpoints. This is also known as server-side rendering (SSR): generating HTML pages on the server when requested and sending them to the client. An adapter is used to run your project on the server and handle these requests.

这种按需渲染允许你:

¥This on-demand rendering allows you to:

  • 在你的应用中实现登录状态的会话。

  • 通过 fetch() 动态调用的 API 渲染数据。

  • 使用适配器将站点部署到主机。

如果你需要以下功能,请考虑在 Astro 项目中启用按需服务器渲染:

¥Consider enabling on-demand server rendering in your Astro project if you need the following:

  • API 端点:创建用作数据库访问、身份验证和授权等任务的 API 端点的特定页面,同时对客户端隐藏敏感数据。

  • 受保护的页面:通过处理服务器上的用户访问,根据用户权限限制对页面的访问。

  • 频繁更改内容:生成单独的页面,无需静态重建你的网站。当页面内容频繁更新时,这非常有用。

¥Official Adapters

Astro 维护 Node.jsVercelNetlifyCloudflare 的官方适配器。

¥Astro maintains official adapters for Node.js, Vercel, Netlify, and Cloudflare.

在我们的集成目录中找到更多 社区维护的适配器(例如 Deno、SST、AWS)。

¥Find even more community-maintained adapters (e.g. Deno, SST, AWS) in our integrations directory.

SSR Adapters

¥Enable on-demand server rendering

Astro 的两种按需渲染输出模式(serverhybrid)都允许你通过尽可能预渲染各个路径来利用静态站点性能,无论你拥有完全动态的应用还是需要按需渲染的大部分静态站点 仅适用于选定的路由。

¥Both of Astro’s on-demand rendering output modes (server and hybrid) allow you to take advantage of static site performance by pre-rendering individual routes whenever possible, whether you have an entirely dynamic app or a mostly static site that needs on-demand rendering only for select routes.

要决定在你的项目中使用哪一个,请选择代表大多数页面和路由将如何渲染的 output 选项:

¥To decide which one to use in your project, choose the output option that represents how most of your pages and routes will be rendered:

  • output: 'server':默认情况下按需渲染。当你的大部分或全部网站或应用应根据请求进行服务器渲染时,请使用此选项。任何单独的页面或端点都可以选择预渲染。

  • output: 'hybrid':默认情况下预渲染为 HTML。当你的网站的大部分内容应该是静态的时,请使用此选项。任何单个页面或端点都可以选择退出预渲染。

因为服务器至少需要按需生成一些页面,所以这两种模式都需要你 添加适配器 来执行服务器功能。

¥Because the server will need to generate at least some pages on demand, both of these modes require you to add an adapter to carry out the server functions.

¥Add an Adapter

要在 serverhybrid 模式下部署项目,你需要添加一个适配器。这是因为这两种模式都需要服务器运行时:在服务器上运行代码以在请求时生成页面的环境。每个适配器都允许 Astro 输出在特定运行时(例如 Vercel、Netlify 或 Cloudflare)上运行项目的脚本。

¥To deploy a project in server or hybrid mode, you need to add an adapter. This is because both of these modes require a server runtime: the environment that runs code on the server to generate pages when they are requested. Each adapter allows Astro to output a script that runs your project on a specific runtime, such as Vercel, Netlify or Cloudflare.

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

¥You can find both official and community adapters in our integrations directory. Choose the one that corresponds to your deployment environment.

¥astro add install

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

¥You can add any of the official adapters 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.

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

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

Terminal window
npx astro add vercel

¥Manual Install

你还可以通过安装软件包并自行更新 astro.config.mjs 来手动添加适配器。

¥You can also add an adapter manually by installing the package and updating astro.config.mjs yourself.

例如,要手动安装 Vercel 适配器:

¥For example, to install the Vercel adapter manually:

  1. Install the adapter to your project dependencies using your preferred package manager:

    Terminal window
    npm install @astrojs/vercel
  2. Add the adapter to your astro.config.mjs file’s import and default export, along with your desired output mode:

    astro.config.mjs
    import { defineConfig } from 'astro/config';
    import vercel from '@astrojs/vercel/serverless';
    export default defineConfig({
    output: 'server',
    adapter: vercel(),
    });

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

¥Configure server or hybrid

要启用按需渲染,你必须将 output 配置更新为两种服务器渲染模式之一。

¥To enable on-demand rendering, you must update your output configuration to one of the two server-rendered modes.

例如,要配置一个高度动态的应用,默认情况下每个页面都按需渲染,请将 output: 'server' 添加到你的 Astro 配置中:

¥For example, to configure a highly dynamic app where every page is rendered on demand by default, add output: 'server' to your Astro config:

astro.config.mjs
import { defineConfig } from 'astro/config';
import node from "@astrojs/node";
export default defineConfig({
output: 'server',
adapter: node({
mode: "standalone"
})
});

选择在 server 模式下进行预渲染

Section titled 选择在 server 模式下进行预渲染

¥Opting-in to pre-rendering in server mode

对于配置为 output: server 的主要由服务器渲染的应用,将 export const prerender = true 添加到任何页面或路由以预渲染静态页面或端点:

¥For a mostly server-rendered app configured as output: server, add export const prerender = true to any page or route to pre-render a static page or endpoint:

src/pages/mypage.astro
---
export const prerender = true;
// ...
---
<html>
<!-- Static, pre-rendered page here... -->
</html>
src/pages/mypage.mdx
---
layout: '../layouts/markdown.astro'
title: 'My page'
---
export const prerender = true;
# This is my static, pre-rendered page
src/pages/myendpoint.js
export const prerender = true;
export async function GET() {
return new Response(
JSON.stringify({
message: `This is my static endpoint`,
}),
);
}

选择退出 hybrid 模式下的预渲染

Section titled 选择退出 hybrid 模式下的预渲染

¥Opting out of pre-rendering in hybrid mode

对于配置为 output: hybrid 的大部分静态站点,将 export const prerender = false 添加到应按需服务器渲染的任何文件中:

¥For a mostly static site configured as output: hybrid, add export const prerender = false to any files that should be server-rendered on demand:

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}`,
}),
);
}

¥On-demand rendering features

¥HTML streaming

通过 HTML 流,文档被分成多个块,按顺序通过网络发送,并按该顺序渲染在页面上。在 serverhybrid 模式下,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. In server or hybrid mode, Astro uses HTML streaming 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.

serverhybrid 模式下,页面或 API 端点可以检查、设置、获取和删除 cookie。

¥In server and hybrid modes, a page or API endpoint 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
---
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 listing page when the product does not exist:

src/pages/my-product.astro
---
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
---
Astro.response.headers.set('Cache-Control', 'public, max-age=3600');
---
<html>
<!-- Page here... -->
</html>

¥Return a Response object

你还可以使用按需渲染直接从任何页面返回 响应 对象。

¥You can also return a Response object directly from any page using on-demand rendering.

下面的示例在数据库中查找 id 后在动态页面上返回 404:

¥The example below returns a 404 on a dynamic page after looking up an id in the database:

src/pages/[id].astro
---
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'
});
}
---
<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 body of the request.

serverhybrid 模式下,你可以从此对象访问非静态生成的页面的附加信息。

¥In both server and hybrid mode, 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
---
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
---
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号