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;
额外优化建议
res.json()是同步方法,不需要添加await,直接调用即可。- 错误返回时使用
error.message替代直接返回error,避免泄露过多服务端内部细节。 - 确认前端请求路径一致性:当前
deletePeople的请求路径为api/people/people-data/student-info/${studentInfo},需确保与后端路由文件的物理路径完全匹配,建议路径开头统一添加/(如/api/people/people-data/student-info/${studentInfo}),避免 baseUrl 拼接时出现路径错误。
内容的提问来源于stack exchange,提问作者Kurama
相关产品推荐
相关产品推荐

