請幫我撰寫一個透過strapi打到他的db的範例
- User
請幫我撰寫一個透過strapi打到他的db的範例
Assistant
我會提供一個使用 Strapi API 存取資料庫的基本範例。這裡使用 JavaScript 展示幾個常見操作:
// 使用 fetch API 存取 Strapi // 1. 獲取所有文章 const fetchArticles = async () => { try { const response = await fetch('http://localhost:1337/api/articles', { method: 'GET', headers: { 'Authorization': 'Bearer YOUR_API_TOKEN', 'Content-Type': 'application/json' } }); const data = await response.json(); return data; } catch (error) { console.error('Error:', error); } }; // 2. 創建新文章 const createArticle = async (articleData) => { try { const response = await fetch('http://localhost:1337/api/articles', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_TOKEN', 'Content-Type': 'application/json' }, body: JSON.stringify({ data: articleData }) }); const data = await response.json(); return data; } catch (error) { console.error('Error:', error); } }; // 3. 更新文章 const updateArticle = async (id, updateData) => { try { const response = await fetch(`http://localhost:1337/api/articles/${id}`, { method: 'PUT', headers: { 'Authorization': 'Bearer YOUR_API_TOKEN', 'Content-Type': 'application/json' }, body: JSON.stringify({ data: updateData }) }); const data = await response.json(); return data; } catch (error) { console.error('Error:', error); } }; // 4. 刪除文章 const deleteArticle = async (id) => { try { const response = await fetch(`http://localhost:1337/api/articles/${id}`, { method: 'DELETE', headers: { 'Authorization': 'Bearer YOUR_API_TOKEN' } }); const data = await response.json(); return data; } catch (error) { console.error('Error:', error); } };使用說明:
- 需要替換
YOUR_API_TOKEN為你的 Strapi API Token - 確保 Strapi 服務器正在運行(預設端口是 1337)
- 根據你的 Strapi 配置調整 API 端點
使用範例:
// 使用範例 const main = async () => { // 獲取所有文章 const articles = await fetchArticles(); console.log('所有文章:', articles); // 創建新文章 const newArticle = await createArticle({ title: '測試文章', content: '這是測試內容' }); console.log('新建文章:', newArticle); // 更新文章 const updatedArticle = await updateArticle(1, { title: '更新後的標題' }); console.log('更新後的文章:', updatedArticle); // 刪除文章 const deletedArticle = await deleteArticle(1); console.log('刪除結果:', deletedArticle); }; main();如果你需要更進階的查詢功能,可以使用 Strapi 的查詢參數:
// 使用過濾器和排序 const fetchFilteredArticles = async () => { const queryParams = new URLSearchParams({ 'filters[title][$contains]': '測試', 'sort[0]': 'createdAt:desc', 'pagination[page]': '1', 'pagination[pageSize]': '10' }).toString(); const response = await fetch( `http://localhost:1337/api/articles?${queryParams}`, { headers: { 'Authorization': 'Bearer YOUR_API_TOKEN' } } ); return await response.json(); };需要注意的是:
- 記得處理錯誤情況
- 在生產環境中使用適當的環境變量來存儲 API Token
- 根據你的需求調整請求的內容和結構
你需要其他特定功能的範例嗎?
- 需要替換
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.