Reputation:
I have a JSON file I want to read from and write to that looks like this:
[
"[email protected]"
]
I want to add info to this file using the fetch()
API. So far, I can only read from this file.
let handle = JSON.stringify(`[email protected]`); // 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);
});
I get no errors (aside from that PUT
comment); ESLint and TSLint don't have any problem with the JS file nor with the JSON file. What am I doing wrong?
Upvotes: 0
Views: 2521
Reputation: 944084
fetch()
is an API for making HTTP requests.
It can't write to files. In particular, nothing can write to arbitrary URLs. (Imagine if it was possible for any browser to write new data to http://www.google.com/
!)
If you want your PUT or POST request to change data on your server, then you must write server-side code to process the request and edit the file.
Upvotes: 5