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

Node.js调用OpenWeatherMap API返回undefined问题咨询

嘿,我来帮你搞定这个问题~你的代码里有两个核心问题导致了undefined的输出,咱们一步步拆解修复:

问题1:API URL的引号语法冲突

你写的URL里,appid="My Api Key"这部分用了双引号嵌套在外层的双引号里,直接导致语法错误(虽然你可能没看到报错,但这会让请求逻辑异常)。解决方法很简单,把内层的双引号换成单引号,或者转义双引号:

  • 方案A(推荐):const location="https://api.openweathermap.org/data/2.5/weather?q=Saulheim&appid='My Api Key'&units=metric";
  • 方案B:const location="https://api.openweathermap.org/data/2.5/weather?q=Saulheim&appid=\"My Api Key\"&units=metric";

问题2:直接打印响应对象而非响应体

https.get回调里的respond是HTTP响应对象,它本身不是API返回的具体数据。你需要通过监听事件来读取响应内容:

  • 用data事件收集响应的二进制片段
  • 用end事件在数据接收完成后拼接、解析并打印
  • 别忘了监听error事件,处理请求失败的情况

修正后的完整代码

const express=require("express");
const https=require("https");
const app=express();

app.get("/",function(req,res){
  // 修复引号问题,这里用单引号包裹API Key
  const location="https://api.openweathermap.org/data/2.5/weather?q=Saulheim&appid='My Api Key'&units=metric";
  
  https.get(location,function(response){
    // 收集响应数据的片段
    let chunks = [];
    
    // 监听data事件,接收二进制数据
    response.on("data", function(chunk){
      chunks.push(chunk);
    });
    
    // 数据接收完成后处理
    response.on("end", function(){
      try {
        // 拼接二进制数据并转成字符串,再解析成JSON对象
        const weatherData = JSON.parse(Buffer.concat(chunks).toString());
        console.log("API响应内容:", weatherData);
      } catch (err) {
        console.error("解析响应失败:", err);
      }
    });
    
    // 监听请求错误
    response.on("error", function(err){
      console.error("请求API失败:", err);
    });
  })
  
  res.send("Everything is fine");
})

app.listen(3000,function(){
  console.log("Server is running on port 3000");
})

额外说明

运行修正后的代码,当你访问http://localhost:3000时,终端就会输出OpenWeatherMap返回的完整天气数据,而不是undefined啦。如果还是有问题,先检查你的API Key是否有效,或者URL里的参数(比如城市名)是否正确~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 17:23:16