无法创建JavaScript对象:API响应数据解析失败求助
问题分析与解决
核心问题
- 流数据未完整拼接:
http模块的响应是流式传输,data事件会多次触发,每次返回的是Buffer片段,你每次创建新数组存储单一片段,且直接将数组传入JSON.parse必然失败。 - URL参数格式错误:请求URL中
directq=London缺少问号,正确格式应为direct?q=London,参数错误会导致API返回非JSON内容,解析自然失败。 - 模块引用混淆:你用
require("http")却命名为https,虽然不影响http请求,但易造成误解。
修正后的代码
const express = require("express"); const app = express(); const http = require("http"); app.get("/", function(req, res) { // 修正URL参数,替换YOUR_API_KEY为你的OpenWeatherMap密钥 const url = "http://api.openweathermap.org/geo/1.0/direct?q=London&units=metric&appid=YOUR_API_KEY"; let rawData = ""; http.get(url, function(response) { console.log(response.statusCode); // 拼接所有数据片段 response.on("data", function(chunk) { rawData += chunk; }); // 数据接收完成后解析 response.on("end", function() { try { const weatherData = JSON.parse(rawData); console.log(weatherData); res.send(`获取到的数据:${JSON.stringify(weatherData)}`); } catch (error) { console.error("JSON解析失败:", error.message); res.send("数据获取失败"); } }); // 处理请求错误 response.on("error", function(error) { console.error("请求出错:", error.message); res.send("请求异常"); }); }); }); app.listen(3000, function() { console.log("Server running in port 3000"); });
关键修改说明
- 用字符串
rawData拼接所有Buffer片段,确保拿到完整响应内容。 - 监听
end事件,在所有数据接收完成后执行JSON.parse,避免解析不完整数据。 - 修正URL参数格式,保证API能正确识别请求参数。
- 添加错误捕获,处理解析失败和请求异常的情况,便于排查问题。
内容的提问来源于stack exchange,提问作者Erol Armstrong
相关产品推荐
相关产品推荐

