数据请求
.astro
文件可以获取远程数据来帮助你生成页面。
¥.astro
files can fetch remote data to help you generate your pages.
Astro 中的 fetch()
Section titled Astro 中的 fetch()¥fetch()
in Astro
所有 Astro 组件 都可以访问其组件脚本中的 全局 fetch()
功能,以使用完整 URL(例如 https://example.com/api)向 API 发出 HTTP 请求。此外,你可以使用 new URL("/api", Astro.url)
构建指向项目页面和端点的 URL,这些页面和端点在服务器上按需渲染。
¥All Astro components have access to the global fetch()
function in their component script to make HTTP requests to APIs using the full URL (e.g. https://example.com/api).
Additionally, you can construct a URL to your project’s pages and endpoints that are rendered on demand on the server using new URL("/api", Astro.url)
.
此获取调用将在构建时执行,并且数据将可供组件模板用于生成动态 HTML。如果启用 SSR 模式,任何提取调用都将在运行时执行。
¥This fetch call will be executed at build time, and the data will be available to the component template for generating dynamic HTML. If SSR mode is enabled, any fetch calls will be executed at runtime.
💡 在 Astro 组件脚本中利用 顶层等待。
¥💡 Take advantage of top-level await inside of your Astro component script.
💡 将获取的数据作为 props 传递给 Astro 和框架组件。
¥💡 Pass fetched data to both Astro and framework components, as props.
框架组件中的 fetch()
Section titled 框架组件中的 fetch()¥fetch()
in Framework Components
fetch()
功能也可在全局范围内供任何 框架组件 使用:
¥The fetch()
function is also globally available to any framework components:
GraphQL 查询
Section titled GraphQL 查询¥GraphQL queries
Astro 还可以使用 fetch()
通过任何有效的 GraphQL 查询来查询 GraphQL 服务器。
¥Astro can also use fetch()
to query a GraphQL server with any valid GraphQL query.
从 Headless CMS 获取
Section titled 从 Headless CMS 获取¥Fetch from a Headless CMS
Astro 组件可以从你最喜欢的 CMS 获取数据,然后将其渲染为你的页面内容。使用 动态路由,组件甚至可以根据你的 CMS 内容生成页面。
¥Astro components can fetch data from your favorite CMS and then render it as your page content. Using dynamic routes, components can even generate pages based on your CMS content.
请参阅我们的 内容管理系统指南,了解有关将 Astro 与无头 CMS(包括 Storyblok、Contentful 和 WordPress)集成的完整详细信息。
¥See our CMS Guides for full details on integrating Astro with headless CMSes including Storyblok, Contentful, and WordPress.
¥Community resources
Learn