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

如何通过fetch与findOneAndDelete实现参数从main.js到server.js再到MongoDB的传递

解决Express+MongoDB中前端传递参数删除文档的问题

我正尝试将参数从main.js(前端)传递到server.js(后端),使用MongoDB的findOneAndDelete方法删除集合中的列表项。技术栈为Express、Node.js和MongoDB(MongoClient),要传递的参数是{'pltnum': item}对象。目前main.js中的代码如下:

function deleteThis(item) {
  fetch('droneInfo', {
    method: 'delete',
    header: {'Content-Type': 'application/json'},
    body: JSON.stringify({ 'pltnum': item })
  })
  .then(res => {
    if (res.ok) {return res....
  })
}

问题分析与解决方案

首先得指出前端fetch里的小疏漏:header应该写成复数headers,这会直接导致后端无法正确解析请求体。接下来分前后端两部分完善代码,确保参数能正常传递并执行删除操作:

1. 前端main.js完善代码

补全fetch的响应处理逻辑,同时修正headers拼写,避免路由匹配问题:

function deleteThis(item) {
  fetch('/droneInfo', { // 加上根路径前缀,确保路由匹配准确
    method: 'DELETE',
    headers: {'Content-Type': 'application/json'}, // 修正为复数headers
    body: JSON.stringify({ pltnum: item })
  })
  .then(res => {
    if (!res.ok) {
      throw new Error('删除请求失败,请稍后重试');
    }
    return res.json(); // 解析后端返回的JSON结果
  })
  .then(data => {
    console.log('删除成功:', data);
    // 这里可以添加UI更新逻辑,比如移除页面上对应的列表项
  })
  .catch(err => {
    console.error('删除出错:', err);
  });
}

2. 后端server.js处理DELETE请求

首先确保Express配置了解析JSON请求体的中间件,然后编写对应路由连接MongoDB执行删除操作:

const express = require('express');
const { MongoClient } = require('mongodb');
const app = express();

// 必须配置这个中间件,才能解析前端传来的JSON请求体
app.use(express.json());

// MongoDB连接信息,根据你的实际配置修改
const mongoUrl = 'mongodb://localhost:27017';
const dbName = '你的数据库名称';
const collectionName = '你的集合名称';

// 处理DELETE请求的路由
app.delete('/droneInfo', async (req, res) => {
  try {
    // 从请求体中获取前端传递的pltnum参数
    const { pltnum } = req.body;
    
    if (!pltnum) {
      return res.status(400).json({ error: 'pltnum参数不能为空' });
    }

    // 连接MongoDB
    const client = await MongoClient.connect(mongoUrl);
    const db = client.db(dbName);
    const collection = db.collection(collectionName);

    // 执行删除操作,根据pltnum匹配文档
    const result = await collection.findOneAndDelete({ pltnum: pltnum });

    client.close(); // 操作完成后关闭数据库连接

    if (result.value) {
      res.json({ success: true, deletedItem: result.value });
    } else {
      res.status(404).json({ success: false, message: '未找到要删除的项' });
    }
  } catch (err) {
    console.error('数据库操作出错:', err);
    res.status(500).json({ error: '服务器内部错误' });
  }
});

// 启动服务器,端口可按需修改
app.listen(3000, () => {
  console.log('服务器运行在http://localhost:3000');
});

关键注意点

  • 前端fetch的URL要和后端路由完全一致,建议加上根路径/droneInfo避免路由匹配混乱;
  • 后端必须通过app.use(express.json())解析JSON请求体,否则req.body会是undefined;
  • 使用async/await处理MongoDB的异步操作,代码更简洁易读,也方便捕获异常;
  • 操作完成后记得关闭MongoDB连接,或者可以考虑使用连接池来优化连接复用;
  • 前后端都要添加错误处理逻辑,既方便调试,也能给用户更友好的反馈。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:32:11