Skip to content

数据获取

.astro 文件可以获取远程数据来帮助你生成页面。

¥.astro files can fetch remote data to help you generate your pages.

¥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.

src/components/User.astro
---
import Contact from '../components/Contact.jsx';
import Location from '../components/Location.astro';
const response = await fetch('https://randomuser.me/api/');
const data = await response.json();
const randomUser = data.results[0];
---
<!-- Data fetched at build can be rendered in HTML -->
<h1>User</h1>
<h2>{randomUser.name.first} {randomUser.name.last}</h2>
<!-- Data fetched at build can be passed to components as props -->
<Contact client:load email={randomUser.email} />
<Location city={randomUser.location.city} />

框架组件中的 fetch()

标题部分 框架组件中的 fetch()

¥fetch() in Framework Components

fetch() 功能也可在全局范围内供任何 框架组件 使用:

¥The fetch() function is also globally available to any framework components:

src/components/Movies.tsx
import type { FunctionalComponent } from 'preact';
const data = await fetch('https://example.com/movies.json').then((response) =>
response.json()
);
// Components that are build-time rendered also log to the CLI.
// When rendered with a client:* directive, they also log to the browser console.
console.log(data);
const Movies: FunctionalComponent = () => {
// Output the result to the page
return <div>{JSON.stringify(data)}</div>;
};
export default Movies;

¥GraphQL queries

Astro 还可以使用 fetch() 通过任何有效的 GraphQL 查询来查询 GraphQL 服务器。

¥Astro can also use fetch() to query a GraphQL server with any valid GraphQL query.

src/components/Film.astro
---
const response = await fetch("https://swapi-graphql.netlify.app/.netlify/functions/index",
{
method: 'POST',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({
query: `
query getFilm ($id:ID!) {
film(id: $id) {
title
releaseDate
}
}
`,
variables: {
id: "ZmlsbXM6MQ==",
},
}),
});
const json = await response.json();
const { film } = json.data;
---
<h1>Fetching information about Star Wars: A New Hope</h1>
<h2>Title: {film.title}</h2>
<p>Year: {film.releaseDate}</p>

¥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

Astro 中文网 - 粤ICP备13048890号