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

如何在Express中实现数组内项目的编辑功能?

Express项目列表编辑(PUT接口)实现方案

先修正现有接口的问题

你当前的DELETE接口存在两个bug,会导致删除功能失效:

  • const { id } = Number(req.params); 写法错误,应提取req.params.id再转换为数字类型
  • webProjects.indexOf(id) 无法找到目标对象,因为数组存储的是对象而非数字ID,需要用findIndex根据对象的ID属性匹配

修正后的DELETE接口:

app.delete('/api/:id', (req, res) => {
    const id = Number(req.params.id);
    const index = webProjects.findIndex(project => project.ID === id);
    if (index === -1) {
        return res.status(404).send('项目不存在');
    }
    webProjects.splice(index, 1);
    res.send('项目已成功删除');
});

实现PUT编辑接口

PUT接口需要通过ID定位要编辑的项目,再通过请求体接收更新后的字段,具体实现如下:

app.put('/api/:id', (req, res) => {
    // 1. 获取要编辑的项目ID并转数字
    const targetId = Number(req.params.id);
    // 2. 从请求体提取更新数据
    const { TITLE, DESCRIPTION, URL } = req.body;

    // 3. 定位目标项目的索引
    const projectIndex = webProjects.findIndex(project => project.ID === targetId);
    if (projectIndex === -1) {
        return res.status(404).send('要编辑的项目不存在');
    }

    // 4. 更新项目字段(仅覆盖传入的字段,未传入的保留原有值)
    const updatedProject = {
        ...webProjects[projectIndex],
        ...(TITLE && { TITLE }),
        ...(DESCRIPTION && { DESCRIPTION }),
        ...(URL && { URL })
    };
    webProjects[projectIndex] = updatedProject;

    // 5. 返回更新后的项目信息
    res.send(updatedProject);
});

代码说明

  • 路由使用/api/:id,通过URL参数指定要编辑的项目ID
  • 用req.body接收更新数据,这是PUT请求的规范写法,比URL参数更安全且支持复杂内容
  • 用findIndex精准匹配目标项目,找不到时返回404状态码提示
  • 采用扩展运算符更新字段,只修改传入的内容,未传入的字段保留原值,提升灵活性

完整修正后的代码

const express = require('express');
const app = express();
const port = 8080;

app.use(express.json());

let webProjects = [
    {ID: 1, TITLE: "React Game", DESCRIPTION: "Tic tac toe game created using Create React App", URL: "http://heroku/myapp/game/"},
    {ID: 2, TITLE: "Online Store", DESCRIPTION: "Online store created with HTML, CSS and Javascript.", URL: "http://git.com/myrepos/shop/index"}
]

app.get('/api', (req, res) => {
    res.send(webProjects)
})

// 优化POST接口(改用请求体传参,更规范)
app.post('/api', (req, res) => {
    const { ID, TITLE, DESCRIPTION, URL } = req.body;
    if (!ID || !TITLE || !DESCRIPTION || !URL) {
        return res.status(400).send('缺少必填字段');
    }
    webProjects.push({ID: Number(ID), TITLE, DESCRIPTION, URL});
    res.send(webProjects);
});

// 修正后的DELETE接口
app.delete('/api/:id', (req, res) => {
    const id = Number(req.params.id);
    const index = webProjects.findIndex(project => project.ID === id);
    if (index === -1) {
        return res.status(404).send('项目不存在');
    }
    webProjects.splice(index, 1);
    res.send('项目已成功删除');
});

// 实现完成的PUT接口
app.put('/api/:id', (req, res) => {
    const targetId = Number(req.params.id);
    const { TITLE, DESCRIPTION, URL } = req.body;

    const projectIndex = webProjects.findIndex(project => project.ID === targetId);
    if (projectIndex === -1) {
        return res.status(404).send('要编辑的项目不存在');
    }

    const updatedProject = {
        ...webProjects[projectIndex],
        ...(TITLE && { TITLE }),
        ...(DESCRIPTION && { DESCRIPTION }),
        ...(URL && { URL })
    };
    webProjects[projectIndex] = updatedProject;

    res.send(updatedProject);
});

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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 00:04:56