如何在Express(Node.js)项目中过滤API非空配料并在EJS展示
问题:如何遍历并展示非空的鸡尾酒配料?
我正在用Express(Node.js)编写后端,从鸡尾酒API获取数据,需要遍历strIngredient1到strIngredient15,跳过值为null的项,在EJS的<li>中展示有效配料列表。
原始代码问题分析
你的EJS循环写法有误:cocktailData.strIngredient + [i]会把字符串和数组拼接,得到"strIngredient1"这类字符串,而非正确访问对应属性。正确的属性访问方式应该使用括号表示法动态获取属性名。
解决方案
方案1:后端预处理数据(推荐)
在Express路由中提前整理好非空配料列表,再传给EJS,让模板逻辑更简洁:
修改你的.js文件:
import express from "express"; import axios from "axios"; import bodyParser from "body-parser"; const app = express(); const port = 3000; app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static("public")); const API_URL = "https://thecocktaildb.com/api/json/v1/1/random.php"; app.get("/", async (req, res) => { try { const response = await axios.get(API_URL); const cocktail = response.data.drinks[0]; // 整理非空配料(可搭配用量) const ingredients = []; for (let i = 1; i <= 15; i++) { const ingredient = cocktail[`strIngredient${i}`]; const measure = cocktail[`strMeasure${i}`]; if (ingredient) { ingredients.push(measure ? `${measure} ${ingredient}` : ingredient); } } res.render("index.ejs", { cocktailData: cocktail, ingredients }); } catch (error) { console.log(error.response); res.status(500).send("获取数据失败"); } }); app.listen(port, () => { console.log(`Server is running at port ${port}`); });
修改EJS文件,直接遍历预处理好的列表:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Cocktail 🍹</title> </head> <body> <h1>Welcome to the Cocktail Application Center</h1> <img src="<%= cocktailData.strDrinkThumb %>" alt="<%= cocktailData.strDrink %>" /> <h2><%= cocktailData.strDrink %></h2> <h3>配料:</h3> <ul> <% ingredients.forEach(ingredient => { %> <li><%= ingredient %></li> <% }) %> </ul> </body> </html>
方案2:直接在EJS中处理
如果不想修改后端,也可以在EJS模板里直接判断并动态访问属性:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Cocktail 🍹</title> </head> <body> <h1>Welcome to the Cocktail Application Center</h1> <img src="<%= cocktailData.strDrinkThumb %>" alt="" /> <ul> <% for(let i = 1 ; i <= 15 ; i++) { %> <% const ingredient = cocktailData[`strIngredient${i}`]; %> <% const measure = cocktailData[`strMeasure${i}`]; %> <% if (ingredient) { %> <li><%= measure ? `${measure} ${ingredient}` : ingredient %></li> <% } %> <% } %> </ul> </body> </html>
关键说明
- 用模板字符串动态生成属性名:
cocktailData[strIngredient${i}],才能正确访问strIngredient1到strIngredient15。 - 添加
if (ingredient)判断,跳过值为null的配料项。 - 可选搭配
strMeasure字段,展示配料用量,让信息更完整。
内容的提问来源于stack exchange,提问作者Mr A KeYz
相关产品推荐
相关产品推荐

