You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js待办列表项目删除操作后重定向异常问题求助

问题:待办列表删除功能重定向失效

开发基于Node.js的待办列表(Todo-List)项目时,删除功能的重定向环节出现异常:点击删除锚点后,页面未按预期刷新当前列表页,反而跳转到带ID的URL,多次尝试均未解决。


现有代码

EJS代码

<button class="Clear" data-doc="<% lists._id %>">Clear List</button>
  
<div class="Assignments">
    <ul class="AssignmentsList">
        <h1><% if(lists.length>0){ %></h1>
            <h1>My lists</h1>
            <% lists.forEach(element =>{ %>
              <h1><%= element.name %></h1>
              <h1> <%= element._id  %></h1>
                <a  href="/list<%= element._id  %>" class="deletee" data-myvalue="<%= element._id %>">Delete</a>
              <% }) %>
            <% } %>
    </ul>
   
</div>
<script >
    
    let trashcan = document.querySelector(".Clear");

    trashcan.addEventListener('click',(e)=>{
        console.log("endpoint");
        let endpoint = `/list/${trashcan.dataset.doc}`;
        fetch(endpoint,{method:'delete'})
        .then(response => response.json())
        .then(data => window.location.href= data.redirect)
        .catch(err => console.log(err));
    })


    let owntrash = document.querySelector('.deletee');

    owntrash.addEventListener('click',(e)=>{
        console.log("fff");
        let endpoint = `/list/${owntrash.dataset.myvalue}`;
        console.log(endpoint);
        fetch(endpoint,{method:'delete'})
        .then(response => response.json())
        .then(data =>  window.location.href= data.redirect)
        .catch(err => console.log(err));
    })

</script>

App代码

app.delete('/list',(req,res)=>{
    const id = req.params.id;
    console.log(id);
   if(id != undefined)
   {
    console.log("single");
   }
   else{
    console.log("gg");
    myList.find()
    .then(result => result.forEach(element => {
        myList.findByIdAndDelete(element._id)
        .catch(err=>console.log(err));
    }
        ))
        .then(result => res.json({redirect: '/'}))
    .catch(err=>console.log(err));
   }
})

app.delete('/list/:id',(req,res)=>{
    const id = req.params.id;
    console.log(id);
    myList.findByIdAndDelete(id)
    .then(resualt => res.json({redirect: '/list'}))
    .catch(err=>console.log(err));
})

app.get('/list',(req,res)=>{
    myList.find()
    .then(result => res.render('list',{lists:result}))
    .catch(err=>console.log(err));
})

问题原因及修复方案

核心问题点

  1. a标签默认跳转抢占逻辑:点击删除锚点时,浏览器优先执行<a>标签的href跳转,导致fetch异步逻辑被中断,无法触发后续重定向。
  2. 删除按钮事件绑定不完整:document.querySelector('.deletee')仅能选中第一个删除按钮,其余按钮无点击事件。
  3. 清空列表路由逻辑错误:app.delete('/list')中req.params.id不存在(路由无参数),且批量删除未等待异步操作完成就返回重定向。
  4. Clear按钮参数无效:lists是数组,lists._id无意义,清空所有列表无需传递ID。

修改后的代码

修正后的EJS代码

<button class="Clear">Clear List</button>
  
<div class="Assignments">
    <ul class="AssignmentsList">
        <% if(lists.length>0){ %>
            <h1>My lists</h1>
            <% lists.forEach(element =>{ %>
                <h1><%= element.name %></h1>
                <h1> <%= element._id  %></h1>
                <a href="/list<%= element._id  %>" class="deletee" data-myvalue="<%= element._id %>">Delete</a>
            <% }) %>
        <% } %>
    </ul>
</div>
<script >
    let trashcan = document.querySelector(".Clear");

    trashcan.addEventListener('click',(e)=>{
        e.preventDefault(); // 阻止默认跳转
        let endpoint = `/list`;
        fetch(endpoint,{method:'delete'})
        .then(response => response.json())
        .then(data => window.location.href= data.redirect)
        .catch(err => console.log(err));
    })

    // 批量绑定所有删除按钮事件
    let owntrashList = document.querySelectorAll('.deletee');
    owntrashList.forEach(owntrash => {
        owntrash.addEventListener('click',(e)=>{
            e.preventDefault(); // 阻止a标签默认跳转
            let endpoint = `/list/${owntrash.dataset.myvalue}`;
            fetch(endpoint,{method:'delete'})
            .then(response => response.json())
            .then(data => window.location.href= data.redirect)
            .catch(err => console.log(err));
        })
    });
</script>

修正后的App代码

// 清空所有列表
app.delete('/list',(req,res)=>{
    myList.find()
    .then(result => {
        // 等待所有删除操作完成
        return Promise.all(result.map(element => myList.findByIdAndDelete(element._id)))
    })
    .then(() => res.json({redirect: '/list'})) // 删除后返回列表页
    .catch(err=>console.log(err));
})

// 删除单个列表
app.delete('/list/:id',(req,res)=>{
    const id = req.params.id;
    myList.findByIdAndDelete(id)
    .then(() => res.json({redirect: '/list'}))
    .catch(err=>console.log(err));
})

app.get('/list',(req,res)=>{
    myList.find()
    .then(result => res.render('list',{lists:result}))
    .catch(err=>console.log(err));
})

内容的提问来源于stack exchange,提问作者Abood

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 03:05:31