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

使用Next.js+Axios调用Edamam API出现400错误求助

食谱搜索功能调用Edamam API出现400错误排查方案

问题背景

使用Next.js开发项目,通过Axios调用Edamam API实现食谱搜索功能,已在.env.local文件中配置对应APP_ID和APP_KEY,但触发搜索时返回Axios 400错误。

错误信息

AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
code: "ERR_BAD_REQUEST"
config: {transitional: {…}, adapter: Array(3), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
message: "Request failed with status code 400"
name: "AxiosError"

相关代码

api.ts

import axios from 'axios';

const API_URL = 'https://api.edamam.com/api/recipes/v2';
const APP_ID = process.env.NEXT_PUBLIC_APP_ID;
const APP_KEY = process.env.NEXT_PUBLIC_APP_KEY;

interface Recipe {
  recipe: {
    uri: string;
    label: string;
    image: string;
    ingredientLines: string[];
  };
}

export const fetchRecipes = async (query: string): Promise<Recipe[]> => {
  try {
    const response = await axios.get(API_URL, {
      params: {
        q: query,
        app_id: APP_ID,
        app_key: APP_KEY,
      },
    });
    return response.data.hits;
  } catch (error) {
    console.error('Error fetching recipes:', error);
    return [];
  }
};

已在.env.local文件中配置对应APP_ID和APP_KEY。

searchBar.tsx

// /components/SearchBar.tsx
import React, { useState } from 'react';

interface SearchBarProps {
  onSearch: (query: string) => void;
}

const SearchBar: React.FC<SearchBarProps> = ({ onSearch }) => {
  const [query, setQuery] = useState('');

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    onSearch(query);
  };

  return ( 
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        placeholder="Search for recipes..."
      />
      <button type="submit">Search</button>
    </form>
  );
};

export default SearchBar;

页面调用部分

<Item>
  <SearchBar onSearch={handleSearch} />
  <RecipeList recipes={recipes} />
</Item>

排查思路与解决方案

1. 确认环境变量加载状态

  • 在fetchRecipes函数中添加日志,打印APP_ID和APP_KEY,验证是否为有效值:
    console.log('APP_ID:', APP_ID, 'APP_KEY:', APP_KEY);
    
  • Next.js中,NEXT_PUBLIC_前缀的环境变量需重启开发服务器才能加载新配置,若修改过.env.local后未重启服务,先重启再测试。

2. 补充API必填参数

Edamam API v2版本要求必须传入type参数(如type=public),当前请求缺少该参数是常见的400错误原因,修改请求参数:

params: {
  q: query,
  app_id: APP_ID,
  app_key: APP_KEY,
  type: 'public' // 新增必填参数
}

3. 拦截空关键词请求

若用户提交空字符串搜索,会触发API参数校验失败,在搜索提交逻辑中添加空值判断:

const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
  e.preventDefault();
  if (query.trim()) { // 仅当关键词非空时发起请求
    onSearch(query);
  }
};

4. 获取详细错误信息

捕获错误时打印API返回的具体错误内容,Edamam通常会明确提示问题原因:

catch (error) {
  if (axios.isAxiosError(error)) {
    console.error('API Error Details:', error.response?.data);
  }
  console.error('Error fetching recipes:', error);
  return [];
}

5. 验证API密钥有效性

直接在浏览器中构造测试URL:https://api.edamam.com/api/recipes/v2?q=chicken&app_id=你的ID&app_key=你的密钥&type=public,若返回401/403,说明密钥无效或过期,需重新在Edamam平台获取。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 02:57:32