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

开发浏览器扩展解析天气API数据时遇SyntaxError错误求助

问题解决:浏览器扩展调用天气API解析JSON报错SyntaxError

错误根源

你遇到的SyntaxError: Unexpected end of input,核心原因是fetch请求设置了mode: "no-cors"。一旦开启这个模式,浏览器会返回一个「不透明响应」——你完全无法读取响应的内容,自然调用res.json()时就没有可解析的JSON数据,直接报输入结束错误。

解决步骤

1. 移除mode: "no-cors"配置

天气API本身支持跨域(CORS),不需要这个限制。修改fetchData里的fetch代码:

let res = await fetch(url, {method: "GET"});

2. 配置扩展的跨域权限

在浏览器扩展的manifest.json中添加目标API的域名权限,确保扩展能正常发起跨域请求:

  • 如果你用的是Manifest V3:
{
  "manifest_version": 3,
  // 其他基础配置(name、version等)
  "host_permissions": [
    "https://api.weatherapi.com/*",
    "https://ipapi.co/*"
  ]
}
  • 如果是Manifest V2:
{
  "manifest_version": 2,
  // 其他基础配置
  "permissions": [
    "https://api.weatherapi.com/*",
    "https://ipapi.co/*"
  ]
}

3. 额外优化建议

  • 避免全局变量污染:把fun函数里的city用let声明,如果不需要全局使用,直接在fetchData里从input取值即可(你当前代码已经这么做了,其实可以完全去掉全局city)。
  • 增加响应状态检查:在解析JSON前判断请求是否成功,能提前捕获API错误(比如key无效、城市不存在):
async function fetchData() {
    let inputEle = document.getElementById("input");
    let location = inputEle.value;
    console.log(location);
    let url = `https://api.weatherapi.com/v1/forecast.json?key=7afae986719f43e0b91135851240406&q=${location}`
    if(location === '') return;
    try{
        let res = await fetch(url, {method: "GET"});
        // 新增:检查响应状态
        if (!res.ok) {
            throw new Error(`请求失败:${res.status} ${res.statusText}`);
        }
        let json = await res.json();
        console.log(json);
        let data = json.current;
        developContainer(data);
        console.log(json.current.temp_c);
    } catch(e) {
        console.log(e);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 03:35:57