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"); })
额外提示
- 避免变量名冲突:外层Express路由回调已经使用
res作为响应对象,内部https.get的响应对象换个名字(比如apiRes)会更清晰 - 处理分块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
相关产品推荐
相关产品推荐

