Node.js中SQL查询用数组过滤无结果,indications值为undefined
解决SQL IN子句数组过滤无结果且indications为undefined的问题
问题根源分析
你遇到的问题有两个核心原因:
indications参数为undefined:说明前端未正确传递该参数到后端,或是后端解析请求体时出现异常。- SQL查询参数传递错误:即便
indications有值,当前代码的参数传递方式也会导致IN子句无法正确匹配数据。
分步解决方法
1. 排查并修复前端传参问题
- 确认前端使用POST请求发送数据(GET请求无法携带请求体)。
- 检查前端请求体中是否包含
indications字段,且该字段是非空数组(避免传递字符串或单个值)。 - 在后端
productsByIndic函数中添加日志,确认请求体内容:
如果日志里没有console.log('收到的请求体:', req.body);indications,直接让前端修正传参逻辑。
2. 修正SQL查询的参数传递
当前代码中db.query的第二个参数传了[indications],这会把整个数组作为单个参数传给第一个?,导致IN子句失效。正确做法是直接传递indications数组:
// 错误写法 await db.query(sql, [indications]) // 正确写法 await db.query(sql, indications)
3. 增加参数校验,避免undefined报错
在模型层和接口层都添加校验,防止indications为undefined或非数组时触发报错:
- 模型层
getProductsOfIndications开头添加校验:if (!Array.isArray(indications) || indications.length === 0) { throw new Error('indications必须是非空数组'); } - 接口层
productsByIndic提前校验参数,直接返回错误响应:const { indications } = req.body; if (!Array.isArray(indications) || indications.length === 0) { return res.json({ status: 400, msg: 'indications参数格式错误,需传入非空数组' }); }
4. 修正返回值格式
原模型层返回[prodByInd]会导致结果嵌套两层数组,前端解析时可能无法正确获取数据,直接返回prodByInd即可:
// 错误写法 return [prodByInd] // 正确写法 return prodByInd
修正后的完整代码
模型层代码
static async getProductsOfIndications(indications){ // 参数校验 if (!Array.isArray(indications) || indications.length === 0) { throw new Error('indications必须是非空数组'); } try { const [prodByInd] = await db.query(` SELECT products.id_product, products.title, products.description, COUNT(comments.id_comment) AS numberOfComments FROM products INNER JOIN product_indications ON products.id_product = product_indications.id_product LEFT JOIN comments ON products.id_product = comments.id_product WHERE product_indications.id_indication IN (${indications.map(()=>'?').join(', ')}) GROUP BY products.id_product, products.title, products.description, products.image_name, products.price ORDER BY numberOfComments DESC LIMIT 0, 25 `, indications); return prodByInd; } catch (error) { console.error(error); throw new Error('Erreur lors de la récupération des produits qui correspondent à ces indications'); } }
接口层代码
static async productsByIndic(req, res, next) { try { console.log('收到的请求体:', req.body); const { indications } = req.body; // 提前校验参数 if (!Array.isArray(indications) || indications.length === 0) { return res.json({ status: 400, msg: 'indications参数格式错误,需传入非空数组' }); } const productsIndications = await productModel.getProductsOfIndications(indications); res.json({ status: 200, result: productsIndications }); } catch (error) { console.error(error); res.json({ status: 500, msg: 'Une erreur s\'est produite lors de l\'affichage des produits des indications choisies!', err: error.message }); } }
内容的提问来源于stack exchange,提问作者Oussama Fathallah
相关产品推荐
相关产品推荐

