【问题标题】:React / Strapi - API request put data in the CMSReact / Strapi - API 请求将数据放入 CMS
【发布时间】:2021-04-04 18:45:18
【问题描述】:

快速提问:我为我的 Strapi CMS 创建了一个 API 获取函数,但似乎无法获得正确的 JSON。 这导致我的 API 调用在 Strapi CMS (200 OK HTTP) 中添加了一个新项目。但没有提供的数据。我猜是 JSON 格式错误导致数据丢失。

什么有效:

  • 授权有效
  • API 请求有效 (200)
  • Strapi CMS 中有一篇空文章

什么不起作用:

  • CMS 中未设置数据。 代码:

  // POST request using fetch with error handling
  function setArticle() {
    const requestOptions = {
      method: 'POST',
      headers: { 
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${state.jwt}` 
      },
      body: JSON.stringify({
        slug: "first-success",
        name: "First successful API request"
      })
    
    };

    fetch('http://localhost:1337/articles', requestOptions)
      .then(async response => {
        const data = await response.json();

        console.log(requestOptions);
        // check for error response
        if (!response.ok) {
            // get error message from body or default to response status
            const error = (data && data.message) || response.status;
            return Promise.reject(error);
        }

        this.setState({ postId: data.id })
    })
    .catch(error => {
        console.error('There was an error!');
    });

  }

我尝试了什么,记录和阅读 Strapi 文档。

【问题讨论】:

    标签: reactjs fetch gatsby strapi


    【解决方案1】:

    问题是,区分大小写。显然,在 Strapi 中创建新的内容类型时,我将实体设置为大写。 (Slug 和 Name) 导致我的 HTTP 请求中的 body 被忽略。

    我更改了没有大写的 Strapi 字段,现在它可以工作了。

      body: JSON.stringify({
        slug: "first-success",
        name: "First successful API request"
      })
    

    【讨论】:

      猜你喜欢
      • 2023-01-07
      • 2020-03-18
      • 1970-01-01
      • 1970-01-01
      • 2018-03-23
      • 1970-01-01
      • 2021-09-05
      • 2015-04-08
      • 2021-01-04
      相关资源
      最近更新 更多