【问题标题】:How to add data into json-server database如何将数据添加到 json-server 数据库中
【发布时间】:2021-11-17 17:48:31
【问题描述】:

这是我的 json-server 数据库。

{
  "users": {
    "sarahedo": {
      "id": "sarahedo",
      "name": "Sarah Edo",
      "avatarURL": "https://pluralsight.imgix.net/author/lg/6f77d113-ea36-4592-814d-9d4acb32f231.jpg",
      "answers": {
        "8xf0y6ziyjabvozdd253nd": "optionOne",
        "6ni6ok3ym7mf1p33lnez": "optionOne",
        "am8ehyc8byjqgar0jgpub9": "optionTwo",
        "loxhs1bqm25b708cmbf3g": "optionTwo"
      },
      "questions": ["8xf0y6ziyjabvozdd253nd", "am8ehyc8byjqgar0jgpub9"]
    },
}

我需要在“问题”中添加新 ID:[“8xf0y6ziyjabvozdd253nd”,“am8ehyc8byjqgar0jgpub9”] 但我无法在 fetch URL 中访问它。

我尝试在浏览器“HTTP://localhost:3000/users/sarahedo”中检查 URL 由于某种原因,我得到了空对象 {}

我想知道如何使用 fetch POST 向其中添加新数据。

【问题讨论】:

  • 分享一下你的js代码,不知道是什么问题很难理解

标签: javascript post fetch json-server


【解决方案1】:

您从http://localhost:3000/users/sarahedo 得到一个空对象的原因是您在.json 文件中错误地定义了您的数据。如果您使用以下数据更正您的.json 文件,您将在浏览器中点击http://localhost:3000/users/sarahedo 看到您的用户obj。

{
  "users": [
    {
      "id": "sarahedo",
      "name": "Sarah Edo",
      "avatarURL": "https://pluralsight.imgix.net/author/lg/6f77d113-ea36-4592-814d-9d4acb32f231.jpg",
      "answers": {
        "8xf0y6ziyjabvozdd253nd": "optionOne",
        "6ni6ok3ym7mf1p33lnez": "optionOne",
        "am8ehyc8byjqgar0jgpub9": "optionTwo",
        "loxhs1bqm25b708cmbf3g": "optionTwo"
      },
      "questions": [
        "8xf0y6ziyjabvozdd253nd",
        "am8ehyc8byjqgar0jgpub9"
      ]
    }
  ]
}

您可以使用以下代码添加新数据,使用 fetch POST:

async function postData(url = '', data = {}) {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    })
    return response.json()
  }

有关获取 POST 的更多详细信息,请查看:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#supplying_request_options

【讨论】:

    猜你喜欢
    • 2017-07-14
    • 2020-09-06
    • 2020-10-25
    • 1970-01-01
    • 2017-11-27
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多