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

使用Spoonacular API开发食谱应用时链接出现404错误求助

问题:食谱链接点击出现404错误

我用栈语言开发食谱生成应用,现有代码能生成食谱链接,但点击时会出现“Cannot GET /Dish%20Diver/undefined”的404错误。调试过链接格式但没解决,链接显示正常却跳不到对应食谱网页。

HTML代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,100;0,9..40,200;0,9..40,300;0,9..40,400;0,9..40,500;0,9..40,600;0,9..40,700;0,9..40,800;0,9..40,900;0,9..40,1000;1,9..40,100;1,9..40,200;1,9..40,300;1,9..40,400;1,9..40,500;1,9..40,600;1,9..40,700;1,9..40,800;1,9..40,900;1,9..40,1000&family=Montserrat:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap" rel="stylesheet">
    <link rel = "icon" href = 
    "images/SVG/Artboard 1Dish Diver Logo.svg" 
    type = "image/x-icon">
    <link rel="stylesheet" href="style.css" type="text/css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="index.js"></script>
    <title>Dish Diver</title>
</head>
<body>
    <div class="content"> 
        <h1 class="title">Dish Diver</h1>
        <label for="ingredients" class="header">Enter Ingredients:</label>
        <input type="text" id="search" class="ing-input" placeholder="Tomatoes, rice, chicken breast, cyan pepper...">
        <button class="search-btn" onclick="getrecipe(document.getElementById('search').value)">Search</button>

        <hr>

        <p class="output">Recipes:</p>
        <div class="recipe-output" id="output">
            <a href="" class="recipe-link" id="sourceLink"></a>
        </div>
    </div>
    <div class="sub-btns">
        <ul>
            <li><a href="" class="favs">Favourites</a></li>
            <li><a href="about.html" class="about">About</a></li>
            <li><a href="" class="logout">Logout</a></li>
        </ul>
    </div>
</body>

</html>

JavaScript代码

// Incorporating the Spoonacular API to the application
const apiKey = 'xxxx'; // Actual api key is hidden

function getrecipe(ingredients) {
  const apiUrl = `https://api.spoonacular.com/recipes/findByIngredients?apiKey=${apiKey}&ingredients=${ingredients}`;

  $.get(apiUrl, function (data) {
    console.log(data); // Check the API response in the console
    displayRecipes(data);
  });
}

// Creating a function to handle the API response and display the recipes on the webpage
function displayRecipes(data) {
  const outputContainer = document.getElementById('output');
  outputContainer.innerHTML = ''; // Clears previous results

  data.forEach((recipe) => {
    const recipeLink = document.createElement('a'); // Create a new anchor element
    recipeLink.href = recipe.sourceUrl;
    recipeLink.textContent = recipe.title;
    recipeLink.className = 'recipe-link';

    outputContainer.appendChild(recipeLink);
  });

  // Calculate the height based on the number of links and set it dynamically
  const linkCount = data.length;
  const minHeight = 50; // Set a minimum height
  const calculatedHeight = linkCount * 20 + minHeight; // Adjust this value as needed

  outputContainer.style.height = `${calculatedHeight}px`;
}

解决方案

问题根源

Spoonacular的findByIngredients接口默认只返回基础食谱信息(比如ID、标题、图片),不包含sourceUrl字段,所以recipe.sourceUrl的值是undefined。浏览器会把undefined当作相对路径,拼接到当前页面URL后,就出现了/Dish%20Diver/undefined的404错误。

修复步骤

方法1:调用API时添加完整信息参数

在findByIngredients接口中添加addRecipeInformation=true参数,让接口返回包含sourceUrl的完整食谱数据:

function getrecipe(ingredients) {
  // 添加addRecipeInformation=true参数获取完整数据
  const apiUrl = `https://api.spoonacular.com/recipes/findByIngredients?apiKey=${apiKey}&ingredients=${ingredients}&addRecipeInformation=true`;

  $.get(apiUrl, function (data) {
    console.log(data);
    displayRecipes(data);
  });
}

方法2:额外调用食谱详情接口

如果不想一次性获取大量数据,可以先拿到食谱ID,再调用/recipes/{id}/information接口获取sourceUrl:

function getrecipe(ingredients) {
  const apiUrl = `https://api.spoonacular.com/recipes/findByIngredients?apiKey=${apiKey}&ingredients=${ingredients}`;

  $.get(apiUrl, function (data) {
    // 遍历每个食谱,获取详情
    Promise.all(data.map(recipe => {
      return $.get(`https://api.spoonacular.com/recipes/${recipe.id}/information?apiKey=${apiKey}`);
    })).then(fullRecipes => {
      displayRecipes(fullRecipes);
    });
  });
}

额外优化:避免空链接

在displayRecipes函数中添加判断,防止sourceUrl为空或undefined的情况,同时设置链接在新窗口打开:

function displayRecipes(data) {
  const outputContainer = document.getElementById('output');
  outputContainer.innerHTML = '';

  data.forEach((recipe) => {
    const recipeLink = document.createElement('a');
    // 处理空链接,默认跳转到锚点
    recipeLink.href = recipe.sourceUrl || '#';
    recipeLink.textContent = recipe.title;
    recipeLink.className = 'recipe-link';
    // 新窗口打开外部链接
    recipeLink.target = "_blank";
    recipeLink.rel = "noopener noreferrer";

    outputContainer.appendChild(recipeLink);
    // 添加换行分隔符,提升可读性
    outputContainer.appendChild(document.createElement('br'));
  });

  const linkCount = data.length;
  const minHeight = 50;
  const calculatedHeight = linkCount * 30 + minHeight; // 调整高度适配换行
  outputContainer.style.height = `${calculatedHeight}px`;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 08:01:23