我有一个要读取和写入的 JSON 文件,如下所示:
[
"test@example.com"
]
Run Code Online (Sandbox Code Playgroud)
我想使用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);
});
Run Code Online (Sandbox Code Playgroud)
我没有收到任何错误(除了那条PUT评论);ESLint 和 TSLint 对 JS 文件和 JSON 文件没有任何问题。我究竟做错了什么?
fetch()是一个用于发出 HTTP 请求的 API 。
它无法写入文件。特别是,没有任何东西可以写入任意 URL。(想象一下,如果任何浏览器都可以向其中写入新数据http://www.google.com/!)
如果您希望 PUT 或 POST 请求更改服务器上的数据,则必须编写服务器端代码来处理请求并编辑文件。