【问题标题】:Using fetch for a POST request to add data to JSON server database使用 fetch 进行 POST 请求以将数据添加到 JSON 服务器数据库
【发布时间】:2021-02-11 11:17:47
【问题描述】:

尝试使用 JSON 服务器向我的假数据库添加新内容。

问题是当我运行该函数时,没有添加输入信息。但是在我的数据库中创建了一个 id 但没有正文内容。

我的代码:

// newName + newNumber are values from user input
 const contactObject = {
        name: newName,
        number: newNumber,
        date: new Date().toISOString(),
        id: persons.length + 1,
      }
      console.log(JSON.stringify(contactObject))

      fetch('http://localhost:3001/phonebook', {
        method: 'POST',
        body: JSON.stringify(contactObject),
      })

上面的控制台日志显示{"name":"test","number":"12345","date":"2020-10-29T01:50:17.345Z","id":9}

我的 JSON 数据库显示

// hardcoded data
 {
      "name": "Mary Poppendieck",
      "number": "39-23-6423122",
      "id": 4
    },
// data from running my create new function
    {
      "id": 5
    }

我预计数据将包括姓名、号码、数据、ID。但只是得到一个 ID。

不确定我在这里做什么,因为这是我第一次进行任何 CRUD 操作。

【问题讨论】:

  • 也许是你的后端代码在做something wrong™
  • 尝试将内容类型设置为application/json

标签: javascript reactjs fetch json-server


【解决方案1】:

需要将以下内容添加到我的功能中。

 headers: {
          "Content-type": "application/json; charset=UTF-8"
        }

完整代码:

fetch('http://localhost:3001/phonebook', {
        method: 'POST',
        body: JSON.stringify(contactObject),
        headers: {
          "Content-type": "application/json; charset=UTF-8"
        }
      })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-22
    • 2019-05-05
    • 2016-12-27
    • 2023-03-15
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    相关资源
    最近更新 更多