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

调用GIPHY API获取GIF时出现TypeError:无法读取images属性

问题

调用两个API从GIPHY获取随机GIF,通过promises数组两次调用自定义的gif()函数,但在gif()函数返回对象时,代码行img: responseJSON.data[0].images.original.url抛出TypeError: Cannot read properties of undefined (reading 'images')。奇怪的是能正常访问responseJSON.data[0].images.original下的其他属性(如size)。相关代码如下:

app.get('/', (req, res) => {

  const gifURL = 'https://api.giphy.com/v1/gifs/search?api_key=key&limit=1&rating=g';
  const wordURL = 'https://api.api-ninjas.com/v1/randomword';
  let options = {
    method: 'GET',
    headers: { 'x-api-key': '' }
  }


  promises = [gif(gifURL), gif(gifURL)];

  async function gif(gifURL) {
    const word = await fetch(wordURL, options);
    const wordJSON = await word.json();
    const response = await fetch(gifURL+'&q='+wordJSON.word);
    const responseJSON = await response.json();
    return {
      img: responseJSON.data[0].images.original.url,
      word: wordJSON.word
    }
  }


  function renderResults() {
    const values = Promise.all(promises)
      .then((values) => {
        console.log(values);
        return res.render('home', {"values": values});
      })

  }

  renderResults();

  
})

解决建议

  • 检查GIPHY API返回是否为空结果:当随机生成的单词没有匹配的GIF时,responseJSON.data会是空数组,此时responseJSON.data[0]为undefined,自然无法读取images属性。建议先做存在性判断:
    if (!responseJSON.data || responseJSON.data.length === 0) {
      // 处理无结果场景,比如重新请求单词再查GIF,或返回默认图
      throw new Error('No GIF found for this word');
    }
    
  • 添加API请求的错误处理:当前代码未处理fetch请求失败的情况(如网络错误、API返回非200状态码),此时responseJSON格式不符合预期,也会触发报错。给每个请求添加状态检查:
    const word = await fetch(wordURL, options);
    if (!word.ok) throw new Error(`Word API request failed: ${word.status}`);
    const wordJSON = await word.json();
    
    const response = await fetch(gifURL+'&q='+wordJSON.word);
    if (!response.ok) throw new Error(`GIF API request failed: ${response.status}`);
    const responseJSON = await response.json();
    
  • 调整函数与变量的声明顺序:当前promises数组声明在gif函数之前,虽然JS有函数提升,但这种写法容易引发逻辑问题,建议把gif函数定义移到promises数组声明前。
  • 排查"能访问其他属性"的矛盾现象:这大概率是测试时的偶发现象——能访问属性时是请求到了有效GIF,报错时是遇到了无结果的请求,两种场景返回的数据结构不同。可以在返回前打印responseJSON确认结构:
    console.log('GIPHY API返回数据:', responseJSON);
    return {
      img: responseJSON.data[0].images.original.url,
      word: wordJSON.word
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 12:23:10