使用获取请求的POST请求将数据添加到JSON服务器数据库

时间:2020-10-29 02:01:22

标签: javascript reactjs fetch json-server

尝试使用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操作时在做什么。

1 个答案:

答案 0 :(得分:0)

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

    @model Model1
    <input asp-for="HiddenSelectedUploadDataType" />
    <div id="partial"></div>
    @section scripts{ 
    <script>
        $(function () {
            $.ajax({
                url: '/TestSlick/GetPartial',
                type: 'POST',
                data: {
                    BookId: $("#HiddenSelectedUploadDataType").val()
                },
                success: function (data) {
                    $('#partial').html(data);
                }
            });  
        })
    </script>
    }
TestSlickController:
     

    public IActionResult TestPartial() {
            Model1 m = new Model1 {  HiddenSelectedUploadDataType="sdsss"};
            return View(m);
        }
        public IActionResult GetPartial(string BookId) {
            ViewData["BookId"] = BookId;
            return PartialView("UpldPopupContentTmpltPartial");
        }

完整代码:

testImplementation 'junit:junit:4.12'
implementation 'junit:junit:4.12'

androidTestImplementation 'com.android.support:support-annotations:28.0.0'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test:rules:1.0.2'