提问者:小点点

使用axious补丁编辑JSON文件中的用户配置文件


我试图使用Axious给用户编辑他们的用户的可能性。我正在使用JSON文件来存储用户信息。

我需要帮助来编写我的API,因此它会更新JSON文件中的currentusers用户信息。登录的用户保存在本地存储中CurrentUser下。

下面是我在EditUser.js中的代码

function updateFunction() {
  let updateData = {
      username : localStorage.getItem('currentUser'),
      age: age.value,
      description: description.value,
      email: email.value,
      phone: phone.value,
      city: city.value,
      zip: zip.value,
      address: address.value,
      password : password.value, 
  }

   axios.patch("http://localhost:2500/editProfile/" +usernameCurent, updateData)
          .then(function(response){
          console.log(response);

          } 

      .then(() => window.location = "../view/userProfile.html"));          

}

下面是我在api.js中的代码

app.patch('/editProfile/:username', (req, res) => {
    fs.readFile(dataPath, "utf8", (err, data) => {
        let parsedData = JSON.parse(data)
        const username = req.params["username"];
        console.log(data)
        parsedData[username] = req.body;
        fs.writeFile(dataPath, JSON.stringify(parsedData), () => {
            res.status(200).send('${username} updated');
        })
    })
})

我需要帮助编写API,以便它更新存储所有用户的storage.json。


共1个答案

匿名用户

使用扩展运算符(https://developer.mozilla.org/en-us/docs/web/javascript/reference/operators/spread_syntax)将允许您获取当前数据并将其与新数据连接起来,如下所示:


app.patch('/editProfile/:username', (req, res) => {
    fs.readFile(dataPath, "utf8", (err, data) => {
        let parsedData = JSON.parse(data)
        const username = req.params["username"];
        console.log(data)

        // this will use the current user, and only update those fields 
        // which are sent in the request body. If only one field is sent, 
        // only that field will be updated.
        const updatedUser = {...parsedData[username], ...req.body}         

        // we then set the parsedData to the new patched user.
        parsedData[username] = updatedUser 

        fs.writeFile(dataPath, JSON.stringify(parsedData), () => {
            res.status(200).send('${username} updated');
        })
    })
})