跳转到内容

数据获取

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

所有 Astro 组件 都可以其在组件脚本中访问 全局 fetch() 函数,以使用完整的 URL(例如 https://example.com/api)向 API 发出 HTTP 请求。此外,你可以使用 new URL("/api", Astro.url) 构造一个指向在服务器上按需渲染的项目页面和端点的 URL。

此 fetch 调用将在构建时执行,并且数据将可用于组件模板以生成动态 HTML。如果启用了 SSR 模式,任何 fetch 调用都将在运行时执行。

💡 善用 Astro 组件脚本中的顶层 await

💡 将获取的数据作为 props 传递给 Astro 和框架组件。

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() 函数也全局可用于任何框架组件

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;

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

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>

Astro 组件可以从你喜欢的 CMS 获取数据,然后将其渲染为你的页面内容。使用动态路由,组件甚至可以根据你的 CMS 内容生成页面。

请参阅我们的 CMS 指南,了解有关将 Astro 与包括 Storyblok、Contentful 和 WordPress 在内的 Headless CMS 集成的完整详细信息。

贡献 社区 赞助