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

无法在Alert框中处理并展示Console World News API响应

解决API调用返回unexpected token "<"错误

这个错误的核心原因很明确:你请求API后拿到的不是预期的JSON数据,而是HTML内容(比如API返回的权限错误页、参数错误提示页),所以调用response.json()时才会报解析错误。

按下面的步骤排查和修复:

1. 先查看API实际返回的内容

修改你的fetch代码,先打印原始响应文本,不要直接转JSON,这样能明确看到API到底返回了什么:

function getNews() {
  const userinput = document.getElementById('topic').value;
  console.log('Getting latest news...');
  fetch(`https://api.worldnewsapi.com/api/v1/news?apikey=MYAPIKEYPURPOSELYBLOCKEDOUT&q=${userinput}`)
    .then(response => {
      // 先打印响应状态码,快速判断请求是否成功
      console.log('API响应状态:', response.status);
      // 获取原始文本内容,查看真实返回
      return response.text();
    })
    .then(rawData => {
      console.log('API原始返回内容:', rawData);
      // 尝试解析JSON
      try {
        const data = JSON.parse(rawData);
        console.log(data);
        const firstNews = data.articles[0];
        console.log(firstNews);
        const title = firstNews.title;
        const description = firstNews.description;
        const url = firstNews.url;
        alert(title + "\n\n" + description + "\n\n" + url);
        sessionStorage.setItem('news', JSON.stringify(firstNews));
      } catch (parseError) {
        console.error('JSON解析失败:', parseError);
      }
    })
    .catch(error => console.error(error));
}

运行后看控制台的API原始返回内容,如果是HTML,里面会明确标注错误原因(比如API密钥无效、参数格式错误)。

2. 修复请求参数的编码问题

用户输入的内容可能包含空格、&、?这类特殊字符,直接拼进URL会破坏请求结构,导致API返回错误页。必须用encodeURIComponent()对用户输入进行编码:

// 修改URL部分,对userinput做编码处理
fetch(`https://api.worldnewsapi.com/api/v1/news?apikey=MYAPIKEYPURPOSELYBLOCKEDOUT&q=${encodeURIComponent(userinput)}`)

3. 验证API密钥有效性

检查你的MYAPIKEYPURPOSELYBLOCKEDOUT是否为有效密钥:

  • 确认密钥没有拼写错误、大小写错误
  • 登录API后台查看密钥是否过期、是否达到调用次数限制
  • 可以直接在浏览器地址栏拼接正确密钥和简单查询词(比如q=tech),访问URL后看返回的是否为JSON数据。

按上面的步骤排查,基本能解决这个问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 22:55:19