javascript - 删除后如何在活动服务器上重新渲染数据 - 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);
};
解决方案
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.`)
}
})
推荐阅读
- amazon-web-services - AWS ELB 访问日志可以格式化吗?
- java - JBehave Serenity:如何管理 baseURL 和相对 URL?
- c - C 编程:带星号的金字塔
- java - optaplanner 何时生成生成的 xml 文件?
- javascript - 遍历对象内的数组,console.log 工作,但我无法让它返回反应元素。
- git - 目录中的 Git 问题克隆
- java - 测试 RestTemplate 拦截器
- javascript - d3.datum 使用选定的选项值
- python - 特殊决策树
- javascript - Javascript中不存在时如何声明CONST