简体   繁体   English

如何将数据添加到 json-server 数据库

[英]How to add data into json-server database

This is my json-server database.这是我的 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"]
    },
}

I need to add new ID in "questions": ["8xf0y6ziyjabvozdd253nd", "am8ehyc8byjqgar0jgpub9"] but I can't access it in fetch URL.我需要在“问题”中添加新 ID:["8xf0y6ziyjabvozdd253nd", "am8ehyc8byjqgar0jgpub9"] 但我无法在获取 URL 中访问它。

I tried to check the URL in browser "HTTP://localhost:3000/users/sarahedo" I get empty object for some reason {}我试图在浏览器“HTTP://localhost:3000/users/sarahedo”中检查 URL 由于某种原因我得到空对象 {}

I want to know how can I add new data to it using fetch POST.我想知道如何使用 fetch POST 向其中添加新数据。

The reason that you get an empty object from http://localhost:3000/users/sarahedo is that you've defined your data in .json file incorrectly.你从http://localhost:3000/users/sarahedo得到一个空对象的原因是你在.json文件中错误地定义了你的数据。 If you correct your .json file with the below data, you'll see your user obj by hitting http://localhost:3000/users/sarahedo in the browser.如果您使用以下数据更正您的.json文件,您将通过在浏览器中点击http://localhost:3000/users/sarahedo来看到您的用户对象。

{
  "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"
      ]
    }
  ]
}

You can either use below code for adding new data, using fetch POST:您可以使用以下代码添加新数据,使用 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()
  }

For more detailed info about fetch POST, check this out: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#supplying_request_options有关获取 POST 的更多详细信息,请查看: https ://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#supplying_request_options

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM