昨天把Review頁面完成後,接下來要做單獨的頁面API資料串接
現在點選個別的遊戲頁面連結是會跳出錯誤的,今天就完成這個部分
先在測試程式裡實作 scripts\strapi-request.mjs
import { writeFileSync } from "node:fs";
import qs from "qs";
const url =
"http://localhost:1337/api/reviews/8" +
"?" +
qs.stringify(
{
filters: { slug: { $eq: "heads-2018" } },
fields: ["slug", "title", "subtitle", "publishedAt"],
populate: { image: { fields: ["url"] } },
pagination: { pageSize: 1, withCount: false },
},
{ encodeValuesOnly: true }
);
console.log("url = ", url);
const response = await fetch(url);
// console.log("response =", response);
const body = await response.json();
// console.log("body =", JSON.stringify(body, null, 2));
const formatted = JSON.stringify(body, null, 2);
const file = "scripts/strapi-response.json";
writeFileSync(file, formatted, "utf-8");
得到的資料格式如下: (scripts/strapi-response.json)
{
"data": {
"id": 8,
"attributes": {
"slug": "hades-2018",
"title": "Hades",
"subtitle": "A Rogue-Like Gem that Ascends to Greatness",
"publishedAt": "2023-05-28T11:00:00.000Z",
"image": {
"data": {
"id": 8,
"attributes": {
"url": "/uploads/hades_2018_bff8e28a82.jpg"
}
}
}
}
},
"meta": {}
}
上面做完,就可以從CMS的資料庫中透過API把需要資料撈出來
接下來把 上面的測試程式直接複製到專案的城市碼理
lib\reviews.js
// 導入 CMS 後 改寫的函式 getReview
export async function getReview(slug) {
const url =
"http://localhost:1337/api/reviews/" +
"?" +
qs.stringify(
{
filters: { slug: { $eq: slug } },
fields: ["slug", "title", "subtitle", "publishedAt", "body"],
populate: { image: { fields: ["url"] } },
pagination: { pageSize: 1, withCount: false },
},
{ encodeValuesOnly: true }
);
console.log("getReview: ", url);
const response = await fetch(url);
const { data } = await response.json();
const { attributes } = data[0];
return {
slug: attributes.slug,
title: attributes.title,
date: attributes.publishedAt.slice(0, "yyy-mm-dd".length),
image: CMD_URL + attributes.image.data.attributes.url,
body: marked(attributes.body, { headIds: false, mangle: false }),
};
}