Fetch() API 未更新 JSON 文件
Fetch() API not updating JSON file
我有一个要读取和写入的 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 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
评论); ESLint 和 TSLint 对 JS 文件和 JSON 文件都没有任何问题。我做错了什么?
fetch()
是 API 用于 发出 HTTP 请求。
无法写入文件。特别是,没有任何内容可以写入任意 URL。 (想象一下,如果任何浏览器都可以将新数据写入 http://www.google.com/
!)
如果您希望您的 PUT 或 POST 请求更改服务器上的数据,那么您必须编写 服务器端代码 来处理请求并编辑文件.
我有一个要读取和写入的 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 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
评论); ESLint 和 TSLint 对 JS 文件和 JSON 文件都没有任何问题。我做错了什么?
fetch()
是 API 用于 发出 HTTP 请求。
无法写入文件。特别是,没有任何内容可以写入任意 URL。 (想象一下,如果任何浏览器都可以将新数据写入 http://www.google.com/
!)
如果您希望您的 PUT 或 POST 请求更改服务器上的数据,那么您必须编写 服务器端代码 来处理请求并编辑文件.