Peticiones HTTP
- Solo se ejecuta en tiempo de compilación o si está habilitado entonces SSR
- No se realizan del lado del cliente
- Se puede usar fetch o Axios
- Es asíncrono por defecto, entonces se puede utilizar
awaitsin agregarasyncen algún lugar - Para facilitar el tipado de la respuesta (response) se puede utilizar la extensión
Paste JSON as Codeo la páginaquicktype
Ejemplo
src\pages\index.astro
---
// Server Side Only or Build Time
import type { PokemonListResponse } from "../interfaces/pokemon-list.response";
import PokemonCard from "../components/PokemonCard.astro";
import MainLayout from "../layouts/MainLayout.astro";
const res = await fetch("https://pokeapi.co/api/v2/pokemon");
const data = (await res.json()) as PokemonListResponse;
---
<MainLayout title="Home | Pokémon Static">
<section>
{
data.results.map((pokemon) => (
<PokemonCard name={pokemon.name} url={pokemon.url} />
))
}
</section>
</MainLayout>
Ejemplo
---
// Server Side Only or Build Time
const response = await fetch("https://rickandmortyapi.com/api/character/");
const data = await response.json();
const characters = data.results;
---
<ul>
{
characters.map((character: any) => (
<li>
<h1>{character.name}</h1>
<img src={character.image} />
</li>
))
}
</ul>