Reputation: 672
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?
Upvotes: 0
Views: 1280
Reputation: 19354
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.
Upvotes: 2