使用 XMLHttpRequest 在 JSON 存储 JSON 文件中编辑用户

Edit a user in a JSON storage JSON file using XMLHttpRequest

我有一个问题,希望这里有人能帮我解决。我正在尝试编辑我的 JSON 文件中的一个用户。因此,我在 HTML 中创建了一个 ID 为“editBtn”的按钮。我的用户存储在文件 storage.JSON 中。登录的用户在 LocalStorage 中保存为“currentUser”。用户名是唯一ID,因此在HTML.

中设置为只读

我已经编写了以下代码,但不幸的是,它不起作用。当我在整个代码中 console.log 时,它似乎在 xhr.addEventListener 之后停止反应。此外,我不确定在开始拼接我的数组并随后发出 PUT 请求时我的逻辑是否正确。

我是编码新手,所以可能会有很多缺陷。

API-增删改查:

app.get('/editProfile', (req, res) => {
    
    var allUsers = JSON.parse(fs.readFileSync("storage.JSON"))
    res.json(allUsers)
})


app.put('/editProfile', (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({message: 'the user is updates as', storage}));
})

editProfile.js

var currentUser = JSON.parse(localStorage.getItem("currentUser"));

document.getElementById("username").value = currentUser.username;
document.getElementById("editPhone").value = currentUser.phone;
document.getElementById("newCity").value = currentUser.city;
document.getElementById("newZip").value = currentUser.zip;
document.getElementById("newAddress").value = currentUser.address;
document.getElementById("newEmail").value = currentUser.email;
document.getElementById("newPassword").value = currentUser.password;



editUser = document.getElementById("editBtn")

editUser.addEventListener('click', ()=> {
    
        const xhr = new XMLHttpRequest();
        xhr.responseType = "json"

        
       
         const username = document.getElementById('username');
         const phone = document.getElementById('editPhone');
         const city = document.getElementById('newCity');
         const zip = document.getElementById('newZip');
         const address = document.getElementById('newAddress');
         const email = document.getElementById('newEmail');
         const password = document.getElementById('newPassword');
 
         var data = {
             username : username.value, 
             phone : phone.value,
             city : city.value,
             zip : zip.value,
             address : address.value,
             email : email.value,
             password : password.value,
         }

        xhr.addEventListener("readystatechange", function() {
        if(this.readyState === 4) {
            var allUsers = this.response;
    
    
            for (i = 0; i < allUsers.length; i++) {
                if (allUsers[i].username === username){
                    allUsers.splice(i,1); 
                    console.log(allUsers)
           
                  
                } }};
    
        xhr.open("PUT", "http://localhost:2500/editProfile", true);
            
        xhr.setRequestHeader("Content-Type", "application/json");
            
  
        xhr.send(JSON.stringify(data));
       
    }) 
})

谢谢你看我的问题

代码嵌套要谨慎。如果您编写函数并从事件处理程序中调用它们,您的代码将更易于阅读和理解。

您面临的问题是您在代码中遗漏了 )。这是我建议的版本:

editUser.addEventListener('click', retrieveAndSendUpdate);

function retriveAndSendUpdate() {
  const username = document.getElementById('username');
  const phone = document.getElementById('editPhone');
  const city = document.getElementById('newCity');
  const zip = document.getElementById('newZip');
  const address = document.getElementById('newAddress');
  const email = document.getElementById('newEmail');
  const password = document.getElementById('newPassword');

  var data = {
    username: username.value,
    phone: phone.value,
    city: city.value,
    zip: zip.value,
    address: address.value,
    email: email.value,
    password: password.value,
  }

  sendUpdate(data);
}

function sendUpdate(data) {
  const xhr = new XMLHttpRequest();
  xhr.responseType = "json"
  xhr.addEventListener("readystatechange", processResponse);
  xhr.open("PUT", "http://localhost:2500/editProfile", true);
  xhr.setRequestHeader("Content-Type", "application/json");
  xhr.send(JSON.stringify(data));
}

function processResponse(e) {
  if (e.readyState === 4) {
    var allUsers = e.response;
    for (i = 0; i < allUsers.length; i++) {
      if (allUsers[i].username === username) {
        allUsers.splice(i, 1);
        console.log(allUsers)
      }
    }
  }
}

您还应该考虑测试在处理用户之前是否确实从服务器返回了任何用户。