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

Node.js中https.get回调内response.on()读取未定义属性错误

解决TypeError: Cannot read properties of undefined (reading 'on')的问题

你遇到的问题是**https.get回调函数的参数定义错误**,导致response变量未定义。

错误根源

https.get()的回调函数仅接收一个参数——服务器返回的响应对象,但你写了两个参数function(req, response):

  • 第一个参数req实际就是响应对象
  • 第二个参数response因此被赋值为undefined,调用response.on()时自然会抛出“无法读取undefined的on属性”的错误

修正后的代码

把回调函数的参数改成单个响应对象(建议换个名字避免和外层Express的res变量混淆):

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

app.get("/", function(req, res) {
    const url = "https://api.openweathermap.org/data/2.5/weather?q=London&appid=my-api-key";

    // 仅保留一个参数,命名为apiRes区分外层的res
    https.get(url, function(apiRes) {
        console.log("blah blah response");

        apiRes.on("data", (data) => {
            console.log(data);
            // const weatherData = JSON.parse(data)
            /* 后续处理代码 */
        })
    });
    res.send("server is up");
})

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

额外提示

  1. 避免变量名冲突:外层Express路由回调已经使用res作为响应对象,内部https.get的响应对象换个名字(比如apiRes)会更清晰
  2. 处理分块JSON数据:OpenWeatherAPI返回的JSON可能分块传输,建议先拼接所有数据再解析:
let rawData = '';
apiRes.on('data', (chunk) => { rawData += chunk; });
apiRes.on('end', () => {
  const weatherData = JSON.parse(rawData);
  console.log(weatherData);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 15:10:23