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

Node.js调用OpenWeather API遇JSON解析错误:Unexpected token o at position 1

问题修复方案

核心错误原因

你遇到的「Unexpected token o in JSON at position 1」错误,主要由两个问题导致:

  • 调用getWeatherData()时没传必填的城市ID和API密钥,请求URL无效,OpenWeather API返回的是HTML错误页面而非合法JSON,JSON.parse解析自然报错。
  • request模块原生不支持Promise,你用await修饰它完全无效,回调里的错误不会被外层try/catch捕获;另外如果后续开启了自动解析JSON的配置,重复调用JSON.parse也会触发这个错误(因为解析后的对象转字符串是[object Object],开头的o就是错误里的token)。

修复步骤及代码示例

方案1:修复request模块的写法

把request包装成支持await的Promise,同时补上必填参数:

const request = require('request');

// 将request包装为Promise,适配async/await
function requestPromise(url) {
  return new Promise((resolve, reject) => {
    request(url, (error, response, body) => {
      if (error) reject(error);
      // 先校验响应状态码,确保请求成功
      if (response.statusCode !== 200) {
        reject(new Error(`API请求失败,状态码:${response.statusCode}`));
        return;
      }
      try {
        const data = JSON.parse(body);
        resolve(data);
      } catch (parseError) {
        reject(new Error(`JSON解析失败:${parseError.message}`));
      }
    });
  });
}

async function getWeatherData(openweather_city_id, openweather_api_key) {
  try {
    // 加上units=metric参数,直接获取摄氏度
    const apiUrl = `https://api.openweathermap.org/data/2.5/weather?id=${openweather_city_id}&appid=${openweather_api_key}&units=metric`;
    const weatherData = await requestPromise(apiUrl);
    // 无需循环weather数组,你要的信息和weather条目无关
    console.log(`地点:${weatherData.name},当前气温:${weatherData.main.temp} 摄氏度`);
  } catch (error) {
    console.error('获取天气数据失败:', error.message);
  }
}

// 调用时传入你的城市ID和API密钥
getWeatherData('你的城市ID', '你的OpenWeatherAPI密钥');

方案2:正确使用Axios(你之前换Axios没解决,大概率是写法错误)

Axios默认自动解析JSON,绝对不能再手动调用JSON.parse,同时要传对参数:

const axios = require('axios');

async function getWeatherData(openweather_city_id, openweather_api_key) {
  try {
    const apiUrl = `https://api.openweathermap.org/data/2.5/weather?id=${openweather_city_id}&appid=${openweather_api_key}&units=metric`;
    // Axios返回的response.data就是解析好的JSON对象
    const response = await axios.get(apiUrl);
    const weatherData = response.data;
    console.log(`地点:${weatherData.name},当前气温:${weatherData.main.temp} 摄氏度`);
  } catch (error) {
    console.error('获取天气数据失败:', error.response?.data?.message || error.message);
  }
}

// 传入你的参数
getWeatherData('你的城市ID', '你的OpenWeatherAPI密钥');

额外注意点

  • 必须加units=metric参数,否则OpenWeather返回的是开尔文温度,不是摄氏度。
  • 可以先把拼接好的URL复制到浏览器测试,确认API返回合法JSON,排除密钥或城市ID无效的问题。

内容的提问来源于stack exchange,提问作者Muhammet Emre Uysal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 05:10:31