Strapi 是一個 headless CMS , 可以將 Content 儲存在其中
Astro.js 可以將 Content 取出並顯示出來
下面我們來說明在 Astro.js 如何整合 Strapi 吧~
An Astro project - If you don’t have an Astro project yet, our Installation guide will get you up and running in no time.
A Strapi CMS server - You can set up a Strapi server on a local environment.
Create a new file at lib/strapi.ts and add the following wrapper function to interact with the Strapi API:
// lib/strapi.ts
interface Props {
endpoint: string;
query?: Record<string, string>;
wrappedByKey?: string;
wrappedByList?: boolean;
}
/**
* Fetches data from the Strapi API
* @param endpoint - The endpoint to fetch from
* @param query - The query parameters to add to the url
* @param wrappedByKey - The key to unwrap the response from
* @param wrappedByList - If the response is a list, unwrap it
* @returns
*/
export default async function fetchApi<T>({
endpoint,
query,
wrappedByKey,
wrappedByList,
}: Props): Promise<T> {
if (endpoint.startsWith('/')) {
endpoint = endpoint.slice(1);
}
const url = new URL(`${import.meta.env.STRAPI_URL}/api/${endpoint}`);
if (query) {
Object.entries(query).forEach(([key, value]) => {
url.searchParams.append(key, value);
});
}
const res = await fetch(url.toString());
let data = await res.json();
if (wrappedByKey) {
data = data[wrappedByKey];
}
if (wrappedByList) {
data = data[0];
}
return data as T;
}
// src/pages/index.astro
---
import fetchApi from '../lib/strapi';
import type Article from '../interfaces/article';
const articles = await fetchApi<Article[]>({
endpoint: 'articles', // the content type to fetch
wrappedByKey: 'data', // the key to unwrap the response
});
---