请求协助:调用Rapid API名言接口时无法获取作者数据
解决RapidAPI名言接口作者信息无法显示的问题
问题根源
- 链式调用的
.then()中,第二个.then()没有返回响应数据,导致后续.then()无法拿到接口返回的对象 - 错误使用数组索引
[1]访问originator字段,实际该字段是对象而非数组
修正后的JavaScript代码
const options = { method: 'GET', headers: { 'X-RapidAPI-Key': '你的API密钥', 'X-RapidAPI-Host': 'quotes15.p.rapidapi.com' } }; function getQuote(){ fetch('https://quotes15.p.rapidapi.com/quotes/random/', options) .then(response => response.json()) .then(response => { // 合并DOM操作,确保能访问完整响应对象 document.getElementById("quote").innerHTML = response.content; // 正确获取作者名称,添加容错处理 document.getElementById("quoteauthor").innerHTML = response.originator?.name || '未知作者'; }) .catch(err => console.error(err)); }
关键修正说明
- 将两个DOM更新操作合并到同一个
.then()中,避免链式调用时丢失响应数据 - 使用
response.originator?.name访问作者名称,?.可选链操作符能避免字段不存在时抛出错误 - 添加
'未知作者'作为默认值,提升代码容错性
调试小技巧
如果不确定接口返回结构,可以先在控制台打印响应内容确认:
.then(response => { console.log(response); // 查看完整响应结构 return response; })
内容的提问来源于stack exchange,提问作者HLee
相关产品推荐
相关产品推荐

