I am trying to do a redirect in an express delete function. When the user hits the "delete" button on front end, I want the backend function to delete the json data and then refresh/redirect the page so the user views an update page with the deleted data missing. On the front-end I have written this code:
$(document).on("click",".del", function(){
const id = $(this).attr("data-name");
$.ajax({
url:"/api/note/"+id,
method: "DELETE"
}).then(function(data){
console.log(data);
})
})
On the back end server side:
app.delete("/api/note/:id", function(req,res){
const delNote = req.params.id;
const delArr = [];
fs.readFile("./db/noteList.json", "utf8",function(err,data){
if(err) throw err;
const noteList = JSON.parse(data);
for(let i=0;i<noteList.length;i++){
if(noteList[i].title==delNote){
delete noteList[i].title;
delete noteList[i].date;
delete noteList[i].notes;
}
else{
delArr.push(noteList[i]);
}
}
fs.writeFile("./db/noteList.json",JSON.stringify(delArr),function(err){
if(err) throw err;
console.log("Added");
res.redirect("/notes"); //NOT WORKING//
});
});