jupiter sailormoon
jupiter sailormoon

Reputation: 301

axios post only saving id and other data not added

I am using json server. When I use either postman or my application, I can see the post effected successfully. However, only the id is recorded and nothing else.

Why is it so? For instance, if I do http://localhost:3001/contacts/?id=48&firstname=rrtty&lastname=yryrty&company=trytryrt&email=tyrtyr&message=tyrtytry

only an id will be created and not my id being inserted.

{
 "contacts": [
    {
      "id": 1,
      "firstname": "Robert",
      "lastname": "Swartez",
      "company": "new company",
      "email": "[email protected]",
      "message": "hello world!"
    },
    {
      "id": 2,
      "firstname": "Lreucy",
      "lastname": "Bagggllmer",
      "company": "new company",
      "email": "[email protected]",
      "message": "does this work!"
    },
    {
      "id": 3
    },
    {
      "id": 4
    },
    {
      "id": 5
    },
    {
      "id": 6
    },
    {
      "id": 7
    },
    {
      "id": 8
    },
    {
      "id": 9
    },
    {
      "id": 10
    },
    {
      "id": 11
    },
    {
      "id": 12
    },
    {
      "id": 13
    },
    {
      "id": 14
    },
    {
      "id": 15
    }
  ]
}

Only the id is being added and the other data are nor being added.

Please note that even with postman, I can see only id being added and not the params

Upvotes: 2

Views: 834

Answers (2)

jupiter sailormoon
jupiter sailormoon

Reputation: 301

I finally found the solution on

https://github.com/typicode/json-server/issues/711

Make sure you set content-type request header to application/json

Upvotes: 0

flemcito
flemcito

Reputation: 92

Try changing your method signature to this:

import axios from 'axios';

export default function callApi(method, url, path, data) {   
  switch(method){
    case 'create':
    {
      alert(`${url}`+ {data})
      return axios.post(`${url}`,{data})  
      .catch(error => {
        throw(error.response);
      });
    }
    case 'getOne':{
      return axios.get(`${url}`+`${path}`+`${data}`)  
      .catch(error => {
        throw(error);
      });
    }

    default:
    {
      return axios.get(`${url}`+`${path}`)  
      .catch(error => {
        throw(error);
      });
    }

  }

};

JS is not a typed language and everything is nullable by default. You can however provide default values if need be... export default function callApi(method = '', url = '', path = '', data = {})

Upvotes: 1

Related Questions