Express.js服务器中matchedId返回undefined,matchedCombination正常
问题排查思路与解决方案
排查思路
- 数据类型不匹配:
combinations数组里的Id是数字类型,但前端传回的Comb_Id是字符串类型,===严格相等比较会因类型差异直接返回false,导致找不到对应组合。 - Id传递流程错误:服务器在渲染
index2页面时,用JSON.stringify(matchedCombination.Id)把数字Id转成了字符串,前端接收到的是字符串格式的Id,回传时保持字符串类型,和数组中的数字Id无法匹配。 - 控制台日志验证:打印
Comb_Id会看到它是带引号的字符串(比如"100"),而数组中对应的Id是数字100,两者类型不一致。
解决方案
方案1:修正Id传递时的类型转换
在post('/')路由中,直接传递原始数字Id,不要用JSON.stringify转换:
// 原代码 var comb_Id = JSON.stringify(matchedCombination.Id); // 修改为 var comb_Id = matchedCombination.Id;
同时确保index2.ejs中传递Id时保留数字类型,回传服务器时不会被自动转为字符串。
方案2:查找时统一数据类型
如果前端传回的Comb_Id无法避免是字符串,在/like和/dislike路由中,将Comb_Id转为数字后再匹配:
// 原代码 const matchedId = combinations.find(c => c.Id === Comb_Id); // 修改为 const matchedId = combinations.find(c => c.Id === Number(Comb_Id));
额外优化:补全缺失字段
combinations数组中部分对象缺少Id和vote字段,会导致点赞逻辑异常,建议补全:
const combinations = [ { dropdown1: 'A', dropdown2: 'F', dropdown3: 'L', result:1, Id:100, vote:0}, { dropdown1: 'A', dropdown2: 'F', dropdown3: 'M', result:2, Id:200, vote:0}, { dropdown1: 'A', dropdown2: 'F', dropdown3: 'N', result:3, Id:300, vote:0}, { dropdown1: 'A', dropdown2: 'F', dropdown3: 'O', result:5, Id:400, vote:0} ]
内容的提问来源于stack exchange,提问作者pythonaire
相关产品推荐
相关产品推荐

