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

使用城市名调用Geonames API获取城市数据返回空数组问题

问题诊断与修复方案

核心问题:未获取输入框的实际值

你的前端代码中,获取城市输入的部分错误地拿到了DOM元素本身,而非输入框的文本值,导致API请求的参数是无效的[object HTMLInputElement],因此返回空结果。

修复步骤

  1. 修正城市值获取逻辑:将获取DOM元素的代码改为获取输入框的文本值
  2. 修正空值判断逻辑:针对字符串类型的城市值做正确的空值校验
  3. 优化错误提示文本:将错误提示从"Invalid zipcode"改为符合场景的"Invalid city name"

完整修复后的app.js代码

const username = "demo";
const baseURL = "http://api.geonames.org/searchJSON"


const submitBtn = document.getElementById("submitBtn");
submitBtn.addEventListener("click", (e) => {
    e.preventDefault();
    const city = document.getElementById("city").value;
    if (city.trim() !== "") {
        getCoords(username, city, baseURL)
            .catch(function (error) {
                console.log(error);
                alert("Invalid city name");
            })
    }
})

const getCoords = async (username, city, baseURL) => {
    const encodedCity = encodeURIComponent(city);
    const res = await fetch(`${baseURL}?q=${encodedCity}&username=${username}`);
    try {
        const data = await res.json();
        console.log(data);
        return data;
    }
    catch (error) {
        console.log("error", error);
    }
};

额外优化建议

  • 统一端口日志:server.js中监听端口为8080,但日志输出的是3000,建议修正为一致:
app.listen(8080, () => {
    console.log("listening on port 8080")
    console.log("Go to http://localhost:8080")
})
  • 参数编码处理:新增encodeURIComponent(city)对城市名称进行URL编码,避免特殊字符导致请求失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 07:05:21