为何指定URL的数据未输出至命令行?(附Express代码)
问题描述
近期学习了Angela Yu的全栈Web开发课程,完全按照课程内容编写了以下Express代码,尝试请求OpenWeatherMap的API数据,但刷新localhost:3000后,命令行无任何预期的API响应输出。
我的代码
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&units=metric&appid={my ID}"); https.get(url, function (response) { console.log(response) }) res.send("server is up and running") }) app.listen(3000, function () { console.log("Server is runniong on port 3000."); })
课程中运行代码后,命令行会输出API的响应信息,但我的命令行除了启动时的Server is runniong on port 3000.,刷新页面后没有任何其他输出。
问题排查与解决
核心原因
当前代码仅发起了HTTPS请求,但未正确监听API响应的数据事件,且直接打印的response是HTTP响应流实例,并非API返回的实际数据,同时存在几处细节问题需要修正。
具体修正步骤
- 处理API响应的数据接收
Node.js的https.get返回的response是可读流,需监听data事件获取二进制数据片段,再通过end事件确认数据接收完成后解析为JSON:
https.get(url, function (response) { let data = ""; // 接收数据片段 response.on("data", function(chunk) { data += chunk; }); // 数据接收完成后解析并打印 response.on("end", function() { const weatherData = JSON.parse(data); console.log(weatherData); }); })
检查API密钥格式
确保{my ID}已替换为你在OpenWeatherMap官网申请的真实API密钥,不要保留大括号占位符。修正拼写错误
启动回调里的Server is runniong拼写错误,应改为Server is running,虽不影响功能,但建议修正以保证代码严谨性。添加请求错误监听
为HTTPS请求添加错误监听,避免请求失败时无任何提示:
https.get(url, function (response) { // ... 数据处理代码 }).on("error", function(err) { console.log("请求出错:", err.message); });
完整修正后的代码
const express = require("express"); const https = require("https"); const app = express(); app.get("/", function (req, res) { // 替换为你的真实OpenWeatherMap API密钥 const apiKey = "你的API密钥"; const url = `https://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid=${apiKey}`; https.get(url, function (response) { let data = ""; response.on("data", function(chunk) { data += chunk; }); response.on("end", function() { try { const weatherData = JSON.parse(data); console.log(weatherData); } catch (err) { console.log("解析数据出错:", err.message); } }); }).on("error", function(err) { console.log("API请求失败:", err.message); }); res.send("server is up and running") }) app.listen(3000, function () { console.log("Server is running on port 3000."); })
运行修正后的代码,刷新localhost:3000后,命令行即可打印出OpenWeatherMap返回的天气数据。
内容的提问来源于stack exchange,提问作者Amir Roshan
相关产品推荐
相关产品推荐

