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

调用Spoonacular API新增diet参数后无返回内容问题求助

问题原因与修复方案

核心错误点

你拼接API请求URL的参数格式错误,属于低级书写失误:
原URL里的参数部分写为:
?timeFrame=day&targetCalories?q=${searchInputTxt}&diet?q=${searchInputTxt1}&exclude=shellfish%2C%20olives
这里targetCalories和diet参数后多了不必要的?q=字符串,导致API无法识别这两个传入的参数,自然无法返回匹配的膳食数据。

修复方法

把fetch的URL参数部分修正为正确格式即可:

function getMealList(){
    let searchInputTxt = document.getElementById('search-input').value.trim();
    let searchInputTxt1 = document.getElementById('search-input1').value.trim();
    // 仅修改了fetch的URL参数部分,删除了两处多余的?q=
    fetch(`https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/mealplans/generate?timeFrame=day&targetCalories=${searchInputTxt}&diet=${searchInputTxt1}&exclude=shellfish%2C%20olives`, {
    "method": "GET",
    "headers": {
    "x-rapidapi-host": "spoonacular-recipe-food-nutrition-v1.p.rapidapi.com",
    "x-rapidapi-key": "81022d9c79mshc06abb7d77ff30fp1e6950jsncae6e5e16400"
    }}).then(response => response.json())
    .then(data => {
        let html = "";
        if(data.meals){
            data.meals.forEach(meal => {
                html += `
                    <div class = "meal-item" data-id = "${meal.id}">
                        <div class = "meal-img">
                            <img src="https://spoonacular.com/recipeImages/${meal.id}-556x370.jpg">
                        </div>
                        <div class = "meal-name">
                            <h3>${meal.title}</h3>
                            <a href = ${meal.sourceUrl} target="_blank" class = "recipe-btn">Get Recipe</a>
                        </div>
                    </div>
                `;
            });
            mealList.classList.remove('notFound');
        } else{
            html = "Sorry, we didn't find any meal!";
            mealList.classList.add('notFound');
        }
        mealList.innerHTML = html;
    })
    // 新增错误捕获,方便后续排查问题
    .catch(err => console.error("请求报错:", err));
}

通用排查思路

  • 调试阶段打印完整请求URL和返回结果:拼接完URL后先打印到控制台,复制到接口测试工具中验证返回值,可快速区分是参数问题、接口权限问题还是前端渲染问题
  • 补充参数合法性校验:提前判断用户输入的卡路里是否为合法数字、膳食类型是否属于API支持的取值范围,避免传非法值导致接口无返回

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 08:12:01