调用词义API无返回内容?技术问题排查求助
问题解决:API请求无内容返回的原因及修复
问题根源
你访问API返回数据的方式错误。https://api.dictionaryapi.dev/api/v2/entries/en/hello的返回结果是数组结构,而非单层对象,你的代码直接通过processedResponse.meanings.definitions.definition访问会得到undefined,所以页面无内容显示。
修复后的代码
<div class="word-img"></div> <button class="word-btn">Click Here</button> <script> const WORD_URL = "https://api.dictionaryapi.dev/api/v2/entries/en/hello"; const word = document.querySelector(".word-img"); async function addNewWord() { try { const promise = await fetch(WORD_URL); const processedResponse = await promise.json(); // API返回的是数组,先取第一个单词条目 const wordData = processedResponse[0]; // meanings和definitions都是数组,取第一个释义组的第一个定义 const firstDefinition = wordData.meanings[0].definitions[0].definition; let text = document.createElement("h1"); text.textContent = firstDefinition; // 优先用textContent避免XSS风险 text.style.fontSize = "25px"; text.style.color = "blue"; word.appendChild(text); console.log(text); } catch (error) { console.error("请求或解析出错:", error); word.innerHTML = "<h1>获取词义失败,请稍后重试</h1>"; } } document.querySelector(".word-btn").addEventListener("click", addNewWord); </script>
关键修改点
- 处理API返回的数组结构:通过
processedResponse[0]获取第一个单词条目 - 正确访问嵌套数组:
meanings[0].definitions[0].definition定位到具体定义内容 - 添加
try/catch块捕获请求或解析错误,便于排查问题 - 用
textContent替代innerHTML,避免潜在的XSS安全风险
内容的提问来源于stack exchange,提问作者user23443961
相关产品推荐
相关产品推荐

