如何解决删除后如何在Active Server上重新呈现数据-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',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);
};
解决方法
每当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.`)
}
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。