【发布时间】:2021-05-09 05:34:32
【问题描述】:
我有 1 个 json 文件:{ "clicks": 0 }
我正在尝试从中检索数据,然后对其进行更新。 GET 有效,但 PUT 无效。
我使用 Typescript,这应该不是问题:
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
现在不工作的更新功能:
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
我不允许对 json 资源执行 PUT 请求吗?我对这个话题不是很熟悉,但是发现了很多资源,这应该是可能的。 GET 按预期工作,PUT 似乎配置得很好,但我不知道为什么它不起作用。
我错过了什么吗?
【问题讨论】:
标签: javascript typescript fetch-api