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

如何在Node.js中用原生JS删除数组特定元素并解决刷新后帖子重现问题

解决Node.js后端存储帖子的删除问题

当前仅通过前端JS删除DOM元素,刷新页面后帖子会重新出现,核心原因是后端存储帖子的数组未同步修改。需要通过前后端配合,实现真正的持久化删除功能。

步骤1:重构后端帖子数据结构(Node.js)

将原存储字符串的数组改为存储带唯一ID的对象,确保删除时能精准定位目标帖子,同时新增删除接口:

import express from "express";
import bodyParser from "body-parser";

const port = 3000;
const app = express();

var userIsAuthorized = false;
// 改为存储带唯一ID的帖子对象
var createPostArray = []
let postIdCounter = 1; // 生成唯一帖子ID的计数器

app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));

function passwordCheck(req, res, next) {
    if (req.body?.password === "XXXX" && req.body?.email === "XXXX") {
        userIsAuthorized = true;
    }
    next();
}

app.use(passwordCheck);

app.get("/", (req, res) => {
    res.render("login.ejs")
});

app.post("/check", (req, res) => {
    if(userIsAuthorized === true) {
        res.redirect("/home");
    } else {
        res.redirect("/");
    }
});

app.get("/home", (req, res) => {
    res.render("index.ejs", {
        PostArray: createPostArray, 
    })
});

app.post("/post", (req, res) => {
    const textPost = req.body["createPost"];
    // 添加带ID的帖子对象到数组
    createPostArray.push({
        id: postIdCounter++,
        content: textPost
    });
    res.redirect("/home");
});

// 新增删除帖子的接口
app.post("/delete-post", (req, res) => {
    const postId = parseInt(req.body.postId);
    // 过滤掉目标帖子,生成新数组(比splice更安全,避免索引混乱)
    createPostArray = createPostArray.filter(post => post.id !== postId);
    // 两种返回方式:刷新页面或返回JSON(用于无刷新删除)
    // res.redirect("/home");
    res.json({success: true});
});

app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});

步骤2:修改EJS模板,绑定帖子ID

给每个帖子容器和删除按钮绑定对应帖子的ID,确保前端能传递正确的删除标识:

<% if (locals.PostArray && PostArray.length > 0) { %>
    <% for (let i = 0; i < PostArray.length; i++) { %>
    <div class="container-new-post" data-post-id="<%= PostArray[i].id %>">
        <div class="new-post post">
            <div class="image-profile-new-post-box">
                <img src="/images/profile.jpg" alt="Profile image" class="image-profile-new-post">
            </div>
            <div class="text-line-new-post">
                <div class="first-line-new-post">
                    <div>
                        <span class="profile-name-new-post"> XXX </span>
                        <span class="profile-user-new-post"> XXX </span>
                    </div>  
                    <div class="incons-new-post">
                        <i class="ri-pencil-line"></i>
                        <!-- 用隐藏表单传递帖子ID,支持两种删除方式 -->
                        <form class="delete-form" style="display: inline;">
                            <input type="hidden" name="postId" value="<%= PostArray[i].id %>">
                            <button type="submit" style="background: none; border: none; padding: 0; cursor: pointer;">
                                <i class="ri-close-line post"></i>
                            </button>
                        </form>
                    </div>
                </div>
                <div class="text-new-post">
                    <form action="/text" method="POST">
                        <input type="text" name="text-post" value="<%= PostArray[i].content %>" class="text-post-edit" contenteditable="false">
                    </form> 
                </div>
                <div class="last-line-new-post">
                    <div class="incons-new-post" id="incons-new-post1">
                        <i class="ri-chat-3-line"></i>
                    </div>
                    <div class="incons-new-post" id="incons-new-post2">
                        <i class="ri-repeat-line"></i>
                    </div>
                    <div class="incons-new-post" id="incons-new-post3">
                        <i class="ri-heart-line"></i>
                    </div>
                    <div class="incons-new-post" id="incons-new-post4">
                        <i class="ri-bar-chart-grouped-line"></i>
                    </div>
                    <div class="incons-new-post" id="incons-new-post5">
                        <i class="ri-save-3-line"></i>
                        <i class="ri-share-line"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <% } %>
<% } %>

步骤3:实现无刷新删除的前端JS

如果不想刷新页面,可通过AJAX发送删除请求,成功后直接移除DOM元素:

<script>
    // 给所有删除表单绑定事件
    document.querySelectorAll(".delete-form").forEach(form => {
        form.addEventListener("submit", async function(e) {
            e.preventDefault(); // 阻止表单默认提交行为
            const postId = this.querySelector('input[name="postId"]').value;
            
            // 发送删除请求到后端
            const response = await fetch("/delete-post", {
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded",
                },
                body: `postId=${postId}`
            });
            
            if (response.ok) {
                // 成功后删除对应的帖子DOM容器
                this.closest(".container-new-post").remove();
            }
        });
    });
</script>

核心要点

  • 后端使用filter方法删除数组元素:这是处理数组删除的安全方式,避免因索引变化导致的错误。
  • 唯一ID的必要性:防止帖子内容重复时误删其他帖子。
  • 两种删除模式可选:表单提交(刷新页面)或AJAX(无刷新),根据需求选择即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 22:55:17