我仍然在练习,我使用nodejs.所以searchingByIngredients
获取食谱数据,并将其存储到食谱,然后它将重定向到显示. exports.display工作完美,因为我已经测试过它,但不知何故,在searchingByIngredients
它不会创建div,食谱不是空的,虽然它说它的阅读,所以我不知道为什么它跳过创建div.
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 });
// Store the response data in a variable
const rec = response.data.hits;
Recipes = rec.map(recipe => ({
label: recipe.recipe.label,
url: recipe.recipe.url,
image: recipe.recipe.image,
}));
// Now 'Recipes' contains the extracted recipe information
console.log('Stored recipe data:', Recipes);
next();
} catch (error) {
console.error('Error:', error.message);
res.status(500).json({ error: 'Internal Server Error' });
}
};
exports.display = async (req, res) => {
try {
const divs = 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">\n${divs.join('\n')}`);
res.send(updatedHTML);
} catch (error) {
console.error('Error in display1:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
}
字符串
1条答案
按热度按时间rt4zxlrg1#
您应该在中间件中将数据附加到请求中,而不是保存到变量中。例如:
字符串
然后在控制器中访问它:
型