0

I have 1 json file: { "clicks": 0 }

I'm trying to retrieve the data from it and then update it. The GET works, but the PUT does not.

I use Typescript which should not be a problem:

  const getClickCounterJsonData = () => fetch(
    'click-counter.json',
    {
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
    }
  )
    .then(response => response.json())
    .then(myJson => myJson);

  // this call is actually added to onClick, but you get the idea
  getClickCounterJsonData().then(data => console.log(data['clicks'])); //this works, returns the actual value of the clicks property

Now the not working updating function:

      const updateClickCounterJsonData = (newData: any) => fetch(
        'click-counter.json',
        {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
          },
          body: JSON.stringify(newData)
        }
      )
        .then(response => response.json())
        .then(myJson => myJson);

    // again in a onClick function
    updateClickCounterJsonData({ clicks: 5 }).catch(error => console.log(error)); // this returns SyntaxError: Unexpected token < in JSON at position 0
   // and also the request in the Network tab says 404 Not Found with a preview text: Cannot PUT click-counter.json

Am I not allowed to do PUT requests to a json resource? I'm not super familiar with the topic, but found a lot of resources that this should be possible. The GET works as expected and the PUT seems to be well configurated but I don't know why it doesn't work.

Am I missing something?

Nikolai
  • 555
  • 7
  • 17
  • Please, see this answer: https://stackoverflow.com/questions/61874969/how-can-i-modify-a-json-file-stored-on-server-from-client-side – Maned Wolf Feb 04 '21 at 21:33

1 Answers1

2

Servers may route requests based on the HTTP request type - for example express/node.js server provides explicit methods to process PUT, POST and GET requests using app.put, app.post and app.get respectively. The logic of this comes under the umbrella of "request routing". If no route is encountered that matches a request pattern, typically the router is coded to fall through to server code that responds with a 404 error.

Hence you can't just change a GET request that works into a PUT request and expect the server to adapt - it would need code changes to do so.

traktor
  • 17,588
  • 4
  • 32
  • 53
  • I see. Okay, thanks for the reply! I will stick with MongoDB or Redis. Apparently, I tried to reinvent the hot water for a simpler/quicker solution. – Nikolai Feb 05 '21 at 02:04