snorlax
snorlax

Reputation: 167

Json server update

I'm using json-server and I'm able to do post and get. But I'am not able to do a update.

In my database, I have this data:

{
  "userRecipes": [
    {
      "id": 1,
      "desc": "dog",
      "flag" : true
    }
  ]
}

I wish to update the flag, for doing this I have used this code but it doesn't work:

loginDataSend.flag = true;     
$http
       (
          {
              method: 'update',
 url: 'http://localhost:3000/userRecipes/' + id,
   data: loginDataSend,
   dataType: "json"
    }
   ).error(funcion()
                 {
                 // Error code here
                 alert("error");
                 })
                 .success(function ()
                 {
                 alert("ok");    
                 });

I thank you for your help.

Upvotes: 5

Views: 12912

Answers (5)

Naeem Akhtar
Naeem Akhtar

Reputation: 1174

You can try.

const result = await fetch(http://localhost:3000/userRecipes/${id}, { method: 'PATCH', body: JSON.stringify({ dataToUpdate}), })

Upvotes: 0

James Winnchester
James Winnchester

Reputation: 54

easyScript is providing the correct answer.

BUT! You have to install the latest version of json server.

The old version doesn't support this kind of PATCH or PUT update.

Old version will always get a 404.

npm install -g json-server

Upvotes: 0

easyScript
easyScript

Reputation: 633

Try this:

const res = await fetch('http://localhost:3000/userRecipes/' + id, {
    method: 'PATCH',
    headers: {
       'Content-Type': 'application/json',
    },
    body: JSON.stringify({ dataToUpdate}),
})

Upvotes: 1

Venkata Ramana
Venkata Ramana

Reputation: 5

You can use PUT method instead 'updade' method, then it automatically converts that into post method and your data will be updated.

Upvotes: 0

Boris Strandjev
Boris Strandjev

Reputation: 46943

update is not a valid HTTP method.

You seem to be striving for REST-based API. The REST paradigm is built upon the HTTP protocol and thus there is a inherent mapping between the HTTP Methods you use and the CRUD operations over the entities you want to achieve.

In HTTP you have the following methods available:

  • POST- generally used for creation under the REST paradigm.
  • PUT - used for updates under the REST paradigm.
  • DELETE - used for deletion.
  • GET - generally used for reading.

In your case you should use PUT because you want to make an update.

Upvotes: 2

Related Questions