Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-2025-04-14· OpenAIHugging Face LMArena Human Preference 140K

請幫我撰寫一個透過strapi打到他的db的範例

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-3-5-sonnet-20241022’s answer.
  1. User

    請幫我撰寫一個透過strapi打到他的db的範例

  2. Assistant

    當然可以!以下是一個簡單的範例,說明如何透過 Strapi 的 API 存取(讀取)和操作(新增)資料庫中的資料。這裡假設你已經有一個運行中的 Strapi 專案,並且有一個 content type 叫做 article。

    1. 使用 Strapi 提供的 REST API 存取資料

    讀取所有 articles

    // 使用 fetch 取得所有 articles
    fetch('http://localhost:1337/api/articles')
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(error => console.error('Error:', error));
    

    新增一筆 article

    fetch('http://localhost:1337/api/articles', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        // 如果有 JWT token,需加上 Authorization
        // 'Authorization': 'Bearer YOUR_JWT_TOKEN'
      },
      body: JSON.stringify({
        data: {
          title: '新文章標題',
          content: '這是文章內容'
        }
      })
    })
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(error => console.error('Error:', error));
    

    2. 在 Strapi 專案內部直接操作 DB(進階)

    如果你要在 Strapi 的 自訂 controller 或 service 內直接操作資料庫,可以這樣寫:

    例如在 ./src/api/article/controllers/article.js:

    module.exports = {
      async find(ctx) {
        // 取得所有 articles
        const articles = await strapi.db.query('api::article.article').findMany();
        ctx.body = articles;
      },
    
      async create(ctx) {
        // 新增一筆 article
        const { title, content } = ctx.request.body;
        const newArticle = await strapi.db.query('api::article.article').create({
          data: {
            title,
            content,
          },
        });
        ctx.body = newArticle;
      },
    };
    

    3. 注意事項

    • 請根據你的 content type 名稱調整 api::article.article。
    • 若有權限設定,請確認 API 權限已開啟。
    • 若要用 GraphQL,語法會不同。

    如果你有更具體的需求(例如:用 Node.js 連 Strapi、或是要用 GraphQL),歡迎補充!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.