前端 nextjs 接入 strapi 作为后端
如何封装请求呢
我们使用的是浏览器的 fetch
不用安装任何库
封装
frontend/src/app/[lang]/utils/fetch-api.tsx
javascript
import qs from "qs";
import { getStrapiURL } from "./api-helpers";
export async function fetchAPI(
path: string,
urlParamsObject = {},
options = {}
) {
try {
// Merge default and user options
const mergedOptions = {
next: { revalidate: 60 },
headers: {
"Content-Type": "application/json",
},
...options,
};
// Build request URL
const queryString = qs.stringify(urlParamsObject);
const requestUrl = `${getStrapiURL(
`/api${path}${queryString ? `?${queryString}` : ""}`
)}`;
// Trigger API call
const response = await fetch(requestUrl, mergedOptions);
const data = await response.json();
return data;
} catch (error) {
console.error(error);
throw new Error(`Please check if your server is running and you set all the required tokens.`);
}
}
getStrapiURL 的内容是这样的:
javascript
export function getStrapiURL(path = '') {
return `${process.env.NEXT_PUBLIC_STRAPI_API_URL || 'http://localhost:1337'}${path}`;
}
如何调用
javascript
const token = process.env.NEXT_PUBLIC_STRAPI_API_TOKEN;
const path = `/articles`;
const urlParamsObject = {
sort: { createdAt: "desc" },
populate: {
cover: { fields: ["url"] },
category: { populate: "*" },
authorsBio: {
populate: "*",
},
},
pagination: {
start: start,
limit: limit,
},
};
const options = { headers: { Authorization: `Bearer ${token}` } };
const responseData = await fetchAPI(path, urlParamsObject, options);
if (start === 0) {
setData(responseData.data);
} else {
setData((prevData: any[] ) => [...prevData, ...responseData.data]);
}
token 的话
token
可以在这里设置
给一些足够的权限就好。