首页 > 解决方案 > 删除后如何在活动服务器上重新渲染数据 - Node/Express

问题描述

我有一个正在运行的活动服务器,我正在尝试执行一个DELETE自动更新数据的请求。在前端,我有捕获活动对象信息的代码,然后向我的DELETE请求then发送GET请求,JSON以便它可以重新呈现数据。我无法弄清楚为什么我必须刷新我的网页以显示该项目已被删除。

router.delete('/notes/:id', (req, res) => {
    // Convert the searched id to a number
    const id = Number(req.params.id);
    // See if the id exists in the array
    const deleted = notes.find(notes => notes.id === id);
    // If it does exist
    if(deleted){
        // Filter for all that don't match the id
        const notesArray = notes.filter(notes => notes.id !== id);
        // Rewrite the json file
        fs.writeFileSync(
            path.join(__dirname, '../../db/db.json'),
            JSON.stringify(notesArray, null, 2)
        );
        // Send success
        res.send(200);
    } else {
        res.status(404).send(`Note you're looking for does not exist.`)
    }
})

编辑:添加前端代码以提供帮助

获取请求

    router.get('/notes', (req, res) => {
        // When user requests the notes
        // Send the notes in a json format
        res.status(200).json(notes);
    })

前端代码

  deleteNote(note.id).then(function() {
    getAndRenderNotes();
    renderActiveNote();
  });

    // Gets notes from the db and renders them to the sidebar
    var getAndRenderNotes = function() {
      return getNotes().then(function(data) {
        renderNoteList(data);
      });
    };

    var getNotes = function() {
      return $.ajax({
        url: "/api/notes",
        method: "GET"
      });
    };

    // Render's the list of note titles
    var renderNoteList = function(notes) {
      $noteList.empty();
    
      var noteListItems = [];
    
      for (var i = 0; i < notes.length; i++) {
        var note = notes[i];
    
        var $li = $("<li class='list-group-item'>").data(note);
        var $span = $("<span>").text(note.title);
        var $delBtn = $(
          "<i class='fas fa-trash-alt float-right text-danger delete-note'>"
        );
    
        $li.append($span, $delBtn);
        noteListItems.push($li);
      }
    
      $noteList.append(noteListItems);
    };

标签: javascriptnode.jsexpressserver

解决方案


304 - Not Modified每当GET请求完成时,我的服务器都会返回一个。修改了代码,以便一旦DELETE发生请求find,如果删除的项目存在于我的数组中,那么我将退出,如果存在,则将redeclare我的notes变量作为filtered数组。从那里我使用过滤后的数组重写我的 JSON 文件。

router.delete('/notes/:id', (req, res) => {
    // Convert the searched id to a number
    const id = Number(req.params.id);
    // See if the number exists in the array
    const deleted = notes.find(notes => notes.id === id);
    // If it does exist
    if(deleted){
        // Filter for all that don't match the id
        notes = notes.filter(notes => notes.id !== id);
        // Rewrite the json file
        fs.writeFileSync(
            path.join(__dirname, '../../db/db.json'),
            JSON.stringify(notes, null, 2)
        );
        // Send new notes file
        res.status(200).send('Success');
    } else {
        res.status(404).send(`Note you're looking for does not exist.`)
    }
})

推荐阅读