You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何仅`search.php?f=${searchInputTxt}`返回结果,MealDB API其他路径无结果?

解决MealDB API多路径请求仅首字母搜索生效的问题

问题根源

你的代码里多个API请求只有search.php?f=${searchInputTxt}有结果,核心原因是MealDB不同API的参数规则差异:

  • filter.php?i=:要求精确匹配食材名称(比如"Chicken Breast"、"Garlic"),模糊输入或非API认可的食材名会返回null
  • search.php?s=:按餐名模糊匹配,但如果输入内容无对应餐品,会返回null
  • search.php?f=:仅匹配餐名首字母,只要输入单个字母就会返回结果,因此最容易命中
  • filter.php?c=:要求精确匹配API定义的菜系名称(比如"Chinese"、"Italian"),拼写错误或非标准名称无结果
  • filter.php?a=:要求精确匹配API定义的地区名称(比如"Indian"、"British"),同样需要严格符合

另外你的代码存在两个潜在问题:

  1. 未处理HTTP错误:fetch不会自动对4xx/5xx状态码抛出异常,若某个请求失败会直接导致Promise.all中断
  2. 无错误捕获:Promise.all没有catch分支,请求失败时页面无任何反馈

代码优化方案

1. 增加错误处理与状态校验

修改请求逻辑,确保捕获HTTP错误并处理请求失败的情况:

function getMealList() {
  let searchInputTxt = document.getElementById('search-input').value.trim();
  const apiPaths = [
    `filter.php?i=${searchInputTxt}`,
    `search.php?s=${searchInputTxt}`,
    `search.php?f=${searchInputTxt}`,
    `filter.php?c=${searchInputTxt}`,
    `filter.php?a=${searchInputTxt}`
  ];

  // 给每个请求添加状态校验和错误捕获
  const requests = apiPaths.map(apiPath =>
    fetch(`https://www.themealdb.com/api/json/v1/1/${apiPath}`)
      .then(response => {
        // 检查HTTP响应状态
        if (!response.ok) {
          throw new Error(`请求失败: ${response.status}`);
        }
        return response.json();
      })
      // 单个请求失败时返回空数据,不影响其他请求
      .catch(error => {
        console.error(apiPath, '请求出错:', error);
        return { meals: null };
      })
  );

  Promise.all(requests)
    .then(responses => {
      let html = "";
      let mealsFound = false;
      responses.forEach(data => {
        if (data.meals) {
          mealsFound = true;
          data.meals.forEach(meal => {
            html += `
              <div class="meal-item" data-id="${meal.idMeal}">
                <div class="meal-img">
                  <img src="${meal.strMealThumb}" alt="food">
                </div>
                <div class="meal-name">
                  <h3>${meal.strMeal}</h3>
                  <a href="#" class="recipe-btn">Get Recipe</a>
                </div>
              </div>
            `;
          });
        }
      });
      if (mealsFound) {
        mealList.classList.remove('notFound');
      } else {
        html = "Sorry, we didn't find any meal!";
        mealList.classList.add('notFound');
      }
      mealList.innerHTML = html;
    })
    // 捕获全局请求错误
    .catch(error => {
      console.error('全局请求出错:', error);
      mealList.innerHTML = "请求出错,请稍后重试";
      mealList.classList.add('notFound');
    });
}

2. 给用户输入做提示(可选)

可以在搜索框旁添加提示,引导用户根据不同搜索类型输入正确内容:

<input type="text" id="search-input" placeholder="输入食材/餐名/菜系/地区或首字母">
<p class="hint">提示:食材/菜系/地区需输入精确名称,首字母搜索请输入单个字母</p>

3. 调试排查(可选)

在响应处理中打印每个API的返回结果,方便排查无结果的原因:

responses.forEach((data, index) => {
  console.log(`API: ${apiPaths[index]} 结果:`, data);
  if (data.meals) {
    // 原渲染逻辑
  }
});

内容的提问来源于stack exchange,提问作者Shaina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 13:32:46