Javascript Fetch()API未更新JSON文件
我有一个JSON文件,我想读取和写入该文件,如下所示:Javascript Fetch()API未更新JSON文件,javascript,fetch-api,Javascript,Fetch Api,我有一个JSON文件,我想读取和写入该文件,如下所示: [ "test@example.com" ] 我想使用fetch()API将信息添加到此文件。到目前为止,我只能从这个文件中读取 let handle = JSON.stringify(`test@example2.com`); // handle is fine irrelevant of "" or `` const url = `../json/emails.json`; // URL is fine const optio
[
"test@example.com"
]
我想使用fetch()
API将信息添加到此文件。到目前为止,我只能从这个文件中读取
let handle = JSON.stringify(`test@example2.com`); // handle is fine irrelevant of "" or ``
const url = `../json/emails.json`; // URL is fine
const options = {
method: `POST`, // PUT return error at second fetch: SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data"
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: handle
};
fetch(url) // this fetch is fine
.then(response => {
if (!response.ok) {
throw new Error(`Error getting the stuff`);
}
return response;
})
.then(r => r.json())
.then(data => {
console.log(`Data: ` + data);
});
fetch(url, options)
.then(response => {
if (!response.ok) {
throw new Error(`Error getting the stuff`);
}
return response;
})
.then(a => a.json())
.then(append => {
console.log(`Data updated: ` + append);
}).catch(err => {
console.error('Request failed: ', err);
});
我没有收到任何错误(除了PUT
comment);ESLint和TSLint对JS文件和JSON文件都没有任何问题。我做错了什么?fetch()
是一种用于发出HTTP请求的API
它无法写入文件。特别是,任何东西都不能写入任意URL。(想象一下,如果任何浏览器都可以将新数据写入http://www.google.com/
!)
如果希望PUT或POST请求更改服务器上的数据,则必须编写服务器端代码来处理请求并编辑文件。fetch()
是用于发出HTTP请求的API
它无法写入文件。特别是,任何东西都不能写入任意URL。(想象一下,如果任何浏览器都可以将新数据写入http://www.google.com/
!)
如果希望PUT或POST请求更改服务器上的数据,则必须编写服务器端代码来处理请求并编辑文件。只是为了澄清-您是否正在尝试使用fetch API更新本地文件?是的。根据@Quentin的说法,这是不可能的。我正在考虑将上述代码翻译成Python或使用Node.js。只是想澄清一下——您是否正在尝试使用fetch API更新本地文件?是的。根据@Quentin的说法,这是不可能的。我正在考虑将上述代码翻译成Python或使用Node.js。