Javascript 如何在DELETE express函数中重定向?
我正在尝试在express delete函数中执行重定向。当用户点击前端的“delete”(删除)按钮时,我希望后端函数删除json数据,然后刷新/重定向页面,以便用户查看一个缺少删除数据的更新页面。在前端,我编写了以下代码:Javascript 如何在DELETE express函数中重定向?,javascript,jquery,node.js,express,Javascript,Jquery,Node.js,Express,我正在尝试在express delete函数中执行重定向。当用户点击前端的“delete”(删除)按钮时,我希望后端函数删除json数据,然后刷新/重定向页面,以便用户查看一个缺少删除数据的更新页面。在前端,我编写了以下代码: $(document).on("click",".del", function(){ const id = $(this).attr("data-name"); $.ajax({
$(document).on("click",".del", function(){
const id = $(this).attr("data-name");
$.ajax({
url:"/api/note/"+id,
method: "DELETE"
}).then(function(data){
console.log(data);
})
})
在后端服务器端:
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//
});
});
app.delete(“/api/note/:id”),函数(req,res){
const delNote=req.params.id;
常数delArr=[];
fs.readFile(“./db/noteList.json”,“utf8”,函数(err,data){
如果(错误)抛出错误;
const noteList=JSON.parse(数据);
对于(设i=0;i您必须在前端重定向/刷新)
$(document).on("click",".del", function(){
const id = $(this).attr("data-name");
$.ajax({
url:"/api/note/"+id,
method: "DELETE"
}).then(function(data){
window.location.reload(); // to refresh
window.location.href = 'your-new-url-here'; // to navigate
})
});
app.delete(“/api/note/:id”),函数(req,res){
const delNote=req.params.id;
常数delArr=[];
fs.readFile(“./db/noteList.json”,“utf8”,函数(err,data){
如果(错误)抛出错误;
const noteList=JSON.parse(数据);
对于(让i=0;这是一条一般的经验法则,我会说永远不要为API调用发出301/302重定向响应。Ajax调用永远不会导致浏览器重定向。302响应只会返回到Javascript,这就是它所发生的一切。从Javascript中,您可以查找3xx响应,获取位置
标题d如果要使浏览器从Javascript重定向,请手动将window.location
设置为新URL。@jfriend00根据配置的方式,AJAX请求通常在重定向之后,并尝试加载下一个URL的内容。请参阅@Phil-重定向之后可能会有AJAX调用(取决于配置),但它不会在浏览器中显示重定向的内容,除非您编写Javascript来执行此操作,因为重定向的内容只会进入您的Javascript。@jfriend00哦,是的,绝对reload()
不是OP想要的。他们希望它重定向到/notes
。重定向客户端。对吗?谢谢你的帮助。但它仍然不起作用。我做了你的编辑。我不再收到404错误,但没有任何刷新。我在“window.location.href='你的新url在这里';//下面放了一个console.log来导航”控制台中没有显示任何内容。不确定为什么会发生这种情况。不确定如何在没有错误的情况下进行调试。
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.status(200);
res.write('Success');
});
});