I just started on my first project, on my way to learn how to code. I've saved all users in a JSON file called storage.JSON and I have the information about the user that is logged in in Local Storage under the name "currentUser". I'm trying to create a button, where the user can delte themself from the JSON file. When I console log throughout my filtering it works. It seems to me that the problem is that the problem can't catch the allUsers variable outside the if-statement. Can anyone help me on how I can solve this problem so I can send the allUsers back to the API in the end of the function.
Here is my code in the API:
app.delete('/deleteProfile', (req, res) => {
var allUsers = JSON.parse(fs.readFileSync("storage.JSON"))
res.json(allUsers)
})
app.post('/deleteProfile', (req, res)=> {
let reqData = req.body;
console.log('Post request virker')
console.log(reqData)
var storage = JSON.parse(fs.readFileSync("storage.JSON"))
storage.push(reqData);
fs.writeFileSync("storage.JSON", JSON.stringify(storage, null, 2));
//console.log(reqData);
res.send(JSON.stringify({mesagge: 'This user has been delete from', storage}));
})
Code in deleteUser.js
deleteUser = document.getElementById("deleteBtn")
deleteUser.addEventListener('click', function() {
const xhr = new XMLHttpRequest();
xhr.responseType = "json"
xhr.addEventListener("readystatechange", function() {
if(this.readyState === 4) {
var allUsers = this.response;
console.log(allUsers);
let currentUser = JSON.parse(localStorage.getItem("currentUser"))
allUsers = allUsers.filter(allUser => allUser.username !== currentUser.username);
console.log(allUsers);
} });
xhr.open("DELETE", "http://localhost:2500/deleteProfile", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(allUser));
})