如何修复React结合Alan AI调用News API时的undefined错误?
解决React结合Alan AI调用News API时articles返回undefined的问题
问题说明
使用React结合Alan AI调用News API获取新闻标题,编写对话脚本后测试,控制台打印articles为undefined,无法正常获取新闻数据。
错误原因
- URL格式错误:基础请求URL已包含
?起始参数,添加source参数时错误使用?拼接,导致URL参数格式无效,API返回异常数据,无法解析出articles。 - 缺失请求错误处理:API请求未处理
error情况,若请求失败直接解析body会导致解构articles失败,返回undefined。 - 重复携带API密钥:拼接URL时重复添加
apiKey参数,可能触发API的参数校验问题。
修复方案
1. 修正Alan AI Studio中的对话脚本
调整URL拼接逻辑,添加错误处理分支:
const API_KEY = "ef1dc56abdf14f858a52b61ada48a4ac" let savedArticles = []; // News by Source intent('Give me the news from $(source* (.*))', (p) => { let NEWS_API_URL = `https://newsapi.org/v2/top-headlines?country=us&apiKey=${API_KEY}`; if(p.source.value) { p.source.value = p.source.value.toLowerCase().split(" ").join("-"); // 用&拼接新参数,移除重复的apiKey NEWS_API_URL = `${NEWS_API_URL}&sources=${p.source.value}` } api.request(NEWS_API_URL, {headers: {"user-agent": 'user agent' }}, (error, response, body) => { // 处理请求错误 if (error) { p.play('Sorry, failed to fetch news. Please try again later.'); return; } let parsedBody; try { parsedBody = JSON.parse(body); } catch (parseError) { p.play('Sorry, failed to parse news data.'); return; } const { totalResults, articles } = parsedBody; if(totalResults == 0 || !articles) { p.play('Sorry, please try searching for news from a different source'); return; } savedArticles = articles; p.play({ command: 'newHeadlines', articles }); p.play(`Here are the latest ${p.source.value} news.`); p.play('Would you like me to read the headlines?'); }); })
2. 增强React端的参数校验(可选)
在onCommand中添加参数存在性校验,避免打印undefined:
useEffect(()=> { alanBtn({ key: alanKey, onCommand: ({ command, articles })=> { if(command === "newHeadlines") { if (articles) { console.log(articles); } else { console.log("未获取到新闻数据"); } } }} ) } , [])
验证修复
重新部署Alan AI Studio脚本,在React应用中测试对话命令,控制台将正常打印News API返回的新闻文章数组。
内容的提问来源于stack exchange,提问作者Waleed Shoaib
相关产品推荐
相关产品推荐

