Home > Mobile >  Vue, Adding Data to local data.json file (json-server)
Vue, Adding Data to local data.json file (json-server)

Time:10-29

I'm working on a small project. the app is written in vue, the data is currently hosted by json-server.

The idea is to be able to post new todos into the json data file. updating the data works just fine, however I'm having issues with posting new elements to the json.

I'm calling a handleSubmit() method and console.log() the project details and the project object.

I'm trying to insert Test Title and Lorem Ipsum dolor sit. as well as a boolean, which is automatically set to 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))

}

The data.json file gets updated, but only the id is set. In this example the entried with id 1 and id 2 existed before.

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

I'm quite new to vue and I'm a little lost on where to debug this issue? the console doesn't respond with an error and the json-server console only outputs POST /projects 201 31.323 ms - 13

EDIT:

as soon I submitted the question to stackoverflow I found my mistake. header: { 'Content-Type': 'application/json' } should be headers.

Anyway, if someone is able to help how to debug issues like those in the future, I'd be very thankful!

CodePudding user response:

as soon I submitted the question to stackoverflow I found my mistake.

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

should be

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

CodePudding user response:

Add this line to header 'Accept': 'application/json'

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