Node.js中searchingByIngredients后display无法生成div的问题
问题排查与解决办法
首要问题:全局变量Recipes的并发冲突
你用全局变量存储菜谱数据,Node.js是单线程异步模型,多个请求同时进来时,后一个请求会直接覆盖前一个的Recipes值。哪怕你看到Recipes不为空,也可能是其他请求的数据,而非当前请求需要的内容——这会导致map生成的div不是你预期的,甚至在并发场景下可能出现数据异常,表现为没生成div。
修复代码:
把数据挂载到当前请求的req对象上,保证每个请求的数据独立:
// 删除全局的let Recipes; exports.searchingByIngredients = async (req, res, next) => { try { const ingr = req.body.arrayData; const queryParams = { q: ingr.join(','), app_id: appId, app_key: appKey, }; const response = await axios.get(apiUrl, { params: queryParams }); const rec = response.data.hits; // 将数据绑定到当前请求对象 req.recipes = rec.map(recipe => ({ label: recipe.recipe.label, url: recipe.recipe.url, image: recipe.recipe.image, })); console.log('Stored recipe data:', req.recipes); next(); } catch (error) { console.error('Error:', error.message); res.status(500).json({ error: 'Internal Server Error' }); } };
更新display接口,从req中获取当前请求的菜谱数据:
exports.display = async (req, res) => { try { // 从当前请求对象读取数据 const divs = req.recipes.map((data) => ` <div id="Recipe"> <div id="left"> <img src="${data.image}"/> </div> <div id="right"> <h1>${data.label}</h1> <a href="${data.url}" target="_blank"> <h2>How to cook?</h2> </a> </div> </div> `); const data = await fs.promises.readFile(filePath, 'utf8'); console.log("reading"); const updatedHTML = data.replace('<div id="nothing">', `<div id="resCon"> ${divs.join('\n')}`); res.send(updatedHTML); } catch (error) { console.error('Error in display1:', error); res.status(500).json({ error: 'Internal Server Error' }); } }
第二个可能:HTML替换匹配失败
如果你的模板HTML里,<div id="nothing">带有多余空格、换行或者额外属性(比如<div id="nothing" class="empty">),replace方法只会匹配完全一致的字符串,导致替换操作没生效,看起来像是跳过了div生成步骤。
验证与修复:
- 先打印
data的内容,确认要替换的字符串和模板里的内容完全一致 - 改用正则表达式匹配,忽略标签内的空格:
const updatedHTML = data.replace(/<div id="nothing"\s*>/, `<div id="resCon"> ${divs.join('\n')}`);
额外提醒
- 永远不要用全局变量传递请求级数据,这是Node.js并发场景下的典型坑
- 可以在
display接口里加个判断,避免无数据时出现报错:
if (!req.recipes || req.recipes.length === 0) { return res.send(data); // 或者返回自定义的无数据提示页面 }
内容的提问来源于stack exchange,提问作者codenoob
相关产品推荐
相关产品推荐

