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

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 data variable you get from the response is a raw string, not a JavaScript object. Trying to destructure lattitude and longitude directly from it will always return undefined.
  • Typos in property names: The API returns latitude (only one 't'), but you wrote lattitude (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 an explanation field in its response. That line will throw an error or log undefined.

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?

  1. Added JSON.parse(data) to convert the raw string response into a usable object, stored as issData.
  2. Fixed the typo from lattitude to latitude to match the API's response structure.
  3. Removed the invalid explanation field access and replaced it with logging the actual coordinates.
  4. Wrapped the parsing logic in a try/catch block to handle any JSON parsing errors gracefully (like if the API returns malformed data).
  5. Improved the message sent to the Discord channel to make the coordinates more readable.

内容的提问来源于stack exchange,提问作者Tom Mccormack

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 07:52:29