컨텐츠로 건너뛰기

데이터 가져오기

.astro 파일은 페이지 생성에 도움이 되는 원격 데이터를 가져올 수 있습니다.

모든 Astro 컴포넌트는 스크립트에서 전역 fetch() 함수를 사용할 수 있습니다. 이 함수는 전체 URL(예: https://example.com/api 또는 Astro.url + "/api")을 사용해 API에 HTTP 요청을 보내기 위해 사용됩니다.

이 fetch 호출은 빌드 시 실행되며, 가져온 데이터는 동적 HTML을 생성하기 위해 컴포넌트 템플릿에서 사용할 수 있습니다. SSR 모드가 활성화되면 모든 fetch 호출이 런타임에 실행됩니다.

💡 Astro 컴포넌트 스크립트에서 최상위 await을 활용하세요.

💡 가져온 데이터를 Astro 및 프레임워크 컴포넌트에 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];
---
<!-- 빌드 시 가져온 데이터를 HTML로 렌더링할 수 있습니다. -->
<h1>User</h1>
<h2>{randomUser.name.first} {randomUser.name.last}</h2>
<!-- 빌드 시 가져온 데이터는 컴포넌트의 props로 전달할 수 있습니다. -->
<Contact client:load email={randomUser.email} />
<Location city={randomUser.location.city} />

프레임워크 컴포넌트의 fetch() 함수

섹션 제목: 프레임워크 컴포넌트의 fetch() 함수

fetch() 함수는 모든 프레임워크 컴포넌트에서 전역적으로 사용할 수도 있습니다.

src/components/Movies.tsx
import type { FunctionalComponent } from 'preact';
const data = await fetch('https://example.com/movies.json').then((response) => response.json());
// 빌드 시 렌더링된 컴포넌트에서는 CLI에 기록됩니다.
// client:* 지시어로 렌더링된 컴포넌트에서는 브라우저 콘솔에 기록됩니다.
console.log(data);
const Movies: FunctionalComponent = () => {
// 결과를 페이지에 출력
return <div>{JSON.stringify(data)}</div>;
};
export default Movies;

Astro에서 유효한 GraphQL 쿼리를 GraphQL 서버에 전달하기 위해 fetch() 함수를 사용할 수도 있습니다.

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>스타워즈: 새로운 희망에 대한 정보를 가져오는 중</h1>
<h2>제목: {film.title}</h2>
<p>출시 연도: {film.releaseDate}</p>

헤드리스 CMS에서 데이터 가져오기

섹션 제목: 헤드리스 CMS에서 데이터 가져오기

Astro 컴포넌트는 즐겨 사용하는 CMS에서 데이터를 가져온 다음 이를 페이지 콘텐츠로 렌더링할 수 있습니다. 동적 경로를 사용하면 컴포넌트가 CMS 콘텐츠를 기반으로 페이지를 생성할 수도 있습니다.

Astro를 Storyblok, Contentful, WordPress 등 다양한 헤드리스 CMS와 통합하는 방법에 대한 자세한 내용은 CMS 안내서를 확인하세요.