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

使用Giphy API的应用中GIF不更新且不匹配搜索词问题

问题修复方案

你的代码存在两个核心问题,以下是具体原因和修复方法:

问题1:GIF与随机词不匹配

random-word-api返回的是数组格式的响应(例如["banana"]),而你在请求Giphy API时,直接把整个axios响应对象responseWord拼接到搜索参数里,导致Giphy接收的搜索词是[object Object],而非实际的随机单词,自然无法匹配对应GIF。

问题2:点击按钮GIF无法更新

由于上述搜索词错误,每次请求Giphy都在搜索无效内容,所以GIF不会随随机词更新;同时,原代码中单词获取失败后仍会执行Giphy请求,逻辑不合理。


修复后的完整代码

let initialButton = document.querySelector("#initial-button");
initialButton.addEventListener("click", getWordAsync);

function displayWord(word) {
  let wordResult = document.querySelector("#word-result");
  wordResult.innerHTML = `Your word is ${word}`;
}

function showGif(response) {
  let gifUrl = response.data.data[0].images.downsized.url;
  let gifResult = document.querySelector("#gif-result");
  gifResult.innerHTML = `<img src="${gifUrl}" alt="Random word GIF">`;
}

async function getWordAsync(event) {
  event.preventDefault();
  let randomWord;
  let gifResult = document.querySelector("#gif-result");
  
  // 重置GIF区域状态
  gifResult.innerHTML = "";

  try {
    // 获取随机单词并提取数组中的第一个元素
    const wordResponse = await axios.get("https://random-word-api.herokuapp.com/word");
    randomWord = wordResponse.data[0];
    displayWord(randomWord);

    // 使用正确的随机单词请求Giphy
    const apiKey = "Hidden to keep it private";
    const gifResponse = await axios.get(
      `https://api.giphy.com/v1/gifs/search?api_key=${apiKey}&q=${randomWord}&limit=1`
    );
    showGif(gifResponse);
  } catch (error) {
    console.error(error);
    if (!randomWord) {
      console.error("Failed to get random word! MÖÖP, MÖÖP!");
    } else {
      console.error("Failed to get GIF! MÖÖP, MÖÖP, MÖÖP!");
      gifResult.innerHTML = `<h2>Shoot, nothing found for "${randomWord}"!</h2>`;
    }
  }
}

关键修改点

  • 提取正确的随机单词:从wordResponse.data[0]获取实际单词,而非直接使用响应对象
  • 合并请求逻辑:将Giphy请求放到单词获取成功的分支中,避免单词获取失败后仍执行无效请求
  • 重置GIF区域:每次点击按钮时清空GIF区域,避免旧内容残留
  • 优化错误提示:根据错误阶段(单词获取/GIF获取)给出对应提示,同时显示实际搜索的单词
  • 添加limit参数:给Giphy请求加上&limit=1,确保只返回一个结果,和你的代码逻辑匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 11:20:17