JavaScript从JSON提取对象失败:Discord API调用ISS接口无法获取经纬度
Fixing ISS Coordinate Extraction from "Where the ISS At" API
Let's break down the issues in your code and fix them step by step:
Key Problems in Your Current Code
- You didn't parse the JSON response before accessing properties: The
datavariable you get from the response is a raw string, not a JavaScript object. Trying to destructurelattitudeandlongitudedirectly from it will always returnundefined. - Typos in property names: The API returns
latitude(only one 't'), but you wrotelattitude(two 't's) — that's why you're getting empty/undefined values. - Non-existent property access: You tried to log
JSON.parse(data).explanation, but the "Where the ISS At" API doesn't include anexplanationfield in its response. That line will throw an error or logundefined.
Corrected Code
if (message.content.startsWith(`${prefix} were is the iss`)) { const https = require('https'); https.get('https://api.wheretheiss.at/v1/satellites/25544', (resp) => { let data = ''; resp.on('data', (chunk) => { data += chunk; }); resp.on('end', () => { try { // Parse the raw string into a JavaScript object first const issData = JSON.parse(data); // Use the correct property name: latitude (not lattitude) const { latitude, longitude } = issData; console.log(`Latitude: ${latitude}`); console.log(`Longitude: ${longitude}`); message.channel.send(`ISS Current Coordinates:\nLatitude: ${latitude}\nLongitude: ${longitude}`); } catch (parseError) { console.log("Error parsing JSON:", parseError.message); message.channel.send("Oops, couldn't fetch ISS coordinates right now."); } }); }).on("error", (err) => { console.log("Error fetching data: " + err.message); message.channel.send("Failed to connect to the ISS API."); }); }
What Changed?
- Added
JSON.parse(data)to convert the raw string response into a usable object, stored asissData. - Fixed the typo from
lattitudetolatitudeto match the API's response structure. - Removed the invalid
explanationfield access and replaced it with logging the actual coordinates. - Wrapped the parsing logic in a
try/catchblock to handle any JSON parsing errors gracefully (like if the API returns malformed data). - Improved the message sent to the Discord channel to make the coordinates more readable.
内容的提问来源于stack exchange,提问作者Tom Mccormack
相关产品推荐
相关产品推荐

