Ben Ben Blog.

建立我的第一個Blog - part 5: Next.js用axios call Strapi api

安裝axios

yarn add axios

建立 axios client

// lib/strapi.ts

import axios from "axios"

export const strapiClient = axios.create({
  baseURL: process.env.STRAPI_URL,
  headers: {
    authorization: `Bearer ${process.env.STRAPI_API_TOKEN}`,
  },
});

使用axios client call api

// lib/api.ts

import { strapiClient } from "./strapi";
import {
  StrapiCollectionTypesResponse,
  StrapiSingleTypesResponse,
} from "@/interfaces/strapi";
import { Information } from "@/interfaces/information";
import { ArticlePopulated } from "@/interfaces/article";

//  get collection with filter
export const getArticleBySlug = async (slug: string) => {
  const articles = await strapiClient.get<
    StrapiCollectionTypesResponse<ArticlePopulated>
  >(`/articles?pLevel&filters[slug][$eq]=${slug}`);
  return articles.data;
};

// get collection without filter
export async function getAllArticles() {
  const articles = await strapiClient.get<
    StrapiCollectionTypesResponse<ArticlePopulated>
  >("/articles?pLevel=2");
  return articles.data;
}

// get single types
export async function getBlogInformation() {
  const infos = await strapiClient.get<StrapiSingleTypesResponse<Information>>(
    "/information"
  );
  return infos.data;
}