Home > Net >  How do I post data to json-server properly in vuejs?
How do I post data to json-server properly in vuejs?

Time:04-07

Posting data to json-server posts with the raw value like so:

    {
      "title": {
        "__v_isShallow": false,
        "dep": {
          "w": 0,
          "n": 0
        },
        "__v_isRef": true,
        "_rawValue": "What is Vuex?",
        "_value": "What is Vuex?"
      },
      "body": {
        "__v_isShallow": false,
        "dep": {
          "w": 0,
          "n": 0
        }
    }

How do i make it to post like so:

{
      "id": 1,
      "title": "Introduction to JavaScript array filter() method",
      "body": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolor, beatae! Alias, possimus asperiores repudiandae ipsam, molestiae doloremque animi magni impedit optio commodi similique consectetur ullam, quaerat nam. Sint, porro dicta? Libero ab officiis explicabo architecto dolorum consequatur eius? Soluta voluptas deleniti corrupti sed pariatur exercitationem error. Veritatis, illo deserunt. Error, dolore inventore doloribus sapiente rerum quas quidem id in. Quisquam mollitia consequuntur animi nostrum. Provident et molestias eaque eligendi illo."
    }
import axios from 'axios'
import { ref } from 'vue'

const addPost = (title, body, tagObj) => {
  const err = ref(null)
  const json = JSON.stringify({ title: title });
  const post = async () => {
    try {
      const res = await axios.post('localhost:3000/posts', { title: title, body: body, tags: tagObj })
    } catch(error) {
      err.value = "There was a problem adding post..."
    }
  }
  return { post, err }
}

export default addPost

CodePudding user response:

It looks like title and body are refs, which you're passing directly to the server.

The solution is to unwrap the ref's value with .value:

const addPost = (title, body, tagObj) => {
                                                                                   
  • Related