【问题标题】:Vue, Adding Data to local data.json file (json-server)Vue,将数据添加到本地 data.json 文件(json-server)
【发布时间】:2021-12-13 22:40:31
【问题描述】:

我正在做一个小项目。该应用程序是用vue编写的,数据目前由json-server托管。

这个想法是能够将新的待办事项发布到 json 数据文件中。更新数据工作得很好,但是我在将新元素发布到 json 时遇到了问题。

我正在调用handleSubmit() 方法和console.log() 项目详细信息和项目对象。

我正在尝试插入 Test TitleLorem Ipsum dolor sit. 以及一个自动设置为 false 的布尔值。

handleSubmit() {

    console.log(this.title, this.details)
    // console: Test Title Lorem Ipsum dolor sit.

    let project = {
        title: this.title,
        details: this.details,
        completed: false,
    }

    console.log(project)
    // console: {title: 'Test Title', details: 'Lorem Ipsum dolor sit.', completed: false}

    fetch('http://localhost:3000/projects', {
        method: 'POST',
        header: { 'Content-Type': 'application/json' },
        body: JSON.stringify(project)
    })
    //.then(() => this.$router.push('/'))
    .catch(err => console.log(err))

}

data.json 文件已更新,但仅设置了 id。在本例中,id 1 和 id 2 的条目之前存在。

[
    {
        id: 1,
        title: "Create new Homepage Banner",
        details: "Lorem Ipsum dolor sit amet goes here.",
        completed: false
    },
    {
        id: 2,
        title: "Very important E-Mail",
        details: "Someone is waiting for your response. Better get this going.",
        completed: true
    },
    {
        id: 3
    }
]

我对 vue 很陌生,我有点迷失在哪里调试这个问题?控制台不响应错误,json-server 控制台只输出POST /projects 201 31.323 ms - 13

编辑:

我将问题提交给 stackoverflow 后,我发现了我的错误。 header: { 'Content-Type': 'application/json' } 应该是 headers

无论如何,如果将来有人能够帮助如何调试类似的问题,我将非常感激!

【问题讨论】:

    标签: vue.js json-server


    【解决方案1】:

    当我将问题提交到 stackoverflow 后,我发现我的错误。

    header: { 'Content-Type': 'application/json' }

    应该是

    headers: { 'Content-Type': 'application/json' }

    【讨论】:

      【解决方案2】:

      将此行添加到标题'Accept': 'application/json'

      fetch('http://localhost:3000/projects', {
          method: 'POST',
          header: { 
            'Content-Type': 'application/json',
            'Accept': 'application/json'      
          },
          body: JSON.stringify(project)
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-17
        • 1970-01-01
        • 2021-03-19
        • 2015-10-23
        • 2020-03-28
        • 2020-04-29
        • 2022-01-13
        相关资源
        最近更新 更多