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

Next.js API路由中req.query参数Undefined的DELETE请求问题

问题分析与解决

核心问题:API路由处理函数参数顺序错误

Next.js 的 API 路由处理函数必须以 (req, res) 作为参数顺序,你当前写反成了 (res, req),导致从错误的对象中读取 req.query,自然返回 undefined。

修复后的后端代码

修改 pages/api/people/people-data/student-info/[studentInfo].js:

import { ObjectId, MongoClient } from "mongodb";

// 修正参数顺序:req 在前,res 在后
async function handler(req, res) {
  const { studentInfo } = req.query; // 现在能正确获取路径参数
  const client = await MongoClient.connect(process.env.MONGODB_URI.toString());
  const db = client.db("people-info");

  if (req.method === "DELETE") {
    try {
      const deleteData = await db
        .collection("student_info")
        .deleteOne({ _id: ObjectId(studentInfo) });

      res.json(deleteData); // res.json 不是异步函数,无需 await
      client.close();
    } catch (error) {
      return res.status(500).json({ message: error.message }); // 返回错误信息更清晰
    }
  }
}

export default handler;

额外优化建议

  1. res.json() 是同步方法,不需要添加 await,直接调用即可。
  2. 错误返回时使用 error.message 替代直接返回 error,避免泄露过多服务端内部细节。
  3. 确认前端请求路径一致性:当前 deletePeople 的请求路径为 api/people/people-data/student-info/${studentInfo},需确保与后端路由文件的物理路径完全匹配,建议路径开头统一添加 /(如 /api/people/people-data/student-info/${studentInfo}),避免 baseUrl 拼接时出现路径错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 22:20:33