如何從 Contentful 中獲取單個條目並按字段值查詢? (How to fetch a single entry from Contentful and query by field value?)


問題描述

如何從 Contentful 中獲取單個條目並按字段值查詢? (How to fetch a single entry from Contentful and query by field value?)

我正在嘗試根據我的條目的名稱自定義字段檢索單個條目。

我嘗試使用具有各種選項的 JS SDK:

client.getEntry("entryID")
    // .where("content_type", "Restaurant")
    // .where("fields.name[match]", "RestaurantName")
    // .all()
    .then(data => console.log('data', data))
    .catch(err => console.log('err', err))

但基於錯誤返回,這表明我只能使用 .getEntry 並傳入條目 ID。

我還查看了使用 axios 發出 HTTP 請求但遇到了類似的問題,只能檢索完整的條目列表或根據條目 ID 過濾。

我可以通過 `field.name === "Slug" 獲取還是我添加的其他自定義字段?


參考解法

方法 1:

Currently the only way to get an entry using getEntry, is to pass in the sys.id value. We use a single controller anytime that we request anything from Contentful. This allows us to set error messages, transform the data returned into the format we want etc. We added to the controller our own getEntry helper function that can be called by

contentfulController.getEntries({
   content_type: 'indexPage',
   'fields.slug[match]': slug,
   include: 3,
   locale: language,
});

Then inside our own getEntry function we grab the first one in the array, and return the object since we always know we will be returning one.

However its important to note that this can cause issues if you have sub strings in the slug. Lets say you have two items with the slugs:

/resource
/resourcelisting

If you query 'fields.slug[match]': '/resource', it will return both items in the results so you should also check which one has the actual slug you want, not part of it.

(by Stretch0Brad Taylor)

參考文件

  1. How to fetch a single entry from Contentful and query by field value? (CC BY‑SA 2.5/3.0/4.0)

#Axios #javascript #content-management-system #contentful






相關問題

如何從 Contentful 中獲取單個條目並按字段值查詢? (How to fetch a single entry from Contentful and query by field value?)

VUE 中的 Axios 承諾失敗,無法讀取未定義的屬性“toUpperCase” (Axios promise in VUE failed with Cannot read property 'toUpperCase' of undefined)

Symfony 4 - 使用 Axios 提交表單? (Symfony 4 - Submit form with Axios?)

Laravel:帶有axios的表單不保存 (Laravel: form with axios not saving)

使用 axios 將用戶圖像上傳到strapi (uploading user image to strapi using axios)

我的 module.exports 返回為 [object Object] (My module.exports return as [object Object])

即使驗證要求無效,數據仍在發送,解決此問題的最佳方法是什麼? (Data is sending even if validation requirements are not valid, whats the best way to approach this?)

如何等到使用 Axios 上傳文件 (How to wait until file is uploaded using Axios)

axios 請求錯誤:使用 Heroku 的 ECONNREFUSED (axios request Error: ECONNREFUSED with Heroku)

為什麼我的 axios 調用即使在解決之後仍返回 undefined? (Why does my axios call return undefined even after then is resolved?)

為什麼在使用 axios.post 時我的頁面上有一個 OBJECT PROMISE (Why i have a OBJECT PROMISE on my page when using axios.post)

如何在使用反應測試庫單擊父組件上的按鈕後測試子組件呈現文本? (How to test the child component render text after the button on the parent component click with react testing library?)







留言討論