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

如何从Node.js的HTTPS GET请求函数中返回响应数据并提取指定JSON字段?

解决Node.js异步函数返回值的问题

Hey there! Let's break down why your code isn't working as expected and fix it step by step.

问题核心:异步操作的特性

The main issue here is that https.get is an asynchronous operation. When you call your authenticate function, it starts the HTTP request but immediately returns undefined (since there's no top-level return statement in the function). The return cdcResponse[0] you wrote is inside the res.on("end") callback—this callback only runs after the request finishes, which happens long after your console.log(connection.SerialNumber) has already executed. That's why you're not seeing the expected value.

解决方案:用Promise封装异步逻辑

The cleanest way to handle this in modern Node.js is to wrap your HTTP request in a Promise, which lets you properly capture and pass along the asynchronous result. Here's how to modify your code:

1. Rewrite the authenticate function to return a Promise

const https = require('https');

function authenticate(uuid, cdcloc) {
  // Return a new Promise to wrap the async request
  return new Promise((resolve, reject) => {
    // Use template literals to make URL building cleaner
    const url = `${cdcloc}/api.php?uuid=${uuid}&auth`;
    https.get(url, (res) => {
      let body = "";

      res.on("data", (chunk) => {
        body += chunk;
      });

      res.on("end", () => {
        try {
          const cdcResponse = JSON.parse(body);
          // Resolve the promise with the desired data
          resolve(cdcResponse[0]);
        } catch (error) {
          // Reject if JSON parsing fails
          reject(error);
        }
      });
    }).on("error", (error) => {
      // Reject if the HTTP request itself fails
      reject(error);
    });
  });
}

2. Call the function with either .then() or async/await

You have two solid, readable options to use this Promise-based function:

Option A: Use .then() for callback-style handling
authenticate('DATATOBEPASSED', 'https://URLHERE')
  .then(connection => {
    // This code runs ONLY after the request succeeds and we have the data
    console.log(connection.SerialNumber);
  })
  .catch(error => {
    // Handle any errors (request failure or JSON parsing issues)
    console.error('Something went wrong:', error.message);
  });
Option B: Use async/await for synchronous-looking code

This is often more intuitive, especially if you have multiple asynchronous steps:

// You must wrap `await` inside an async function
async function fetchAndLogSerialNumber() {
  try {
    // Wait for the authenticate function to resolve with the data
    const connection = await authenticate('DATATOBEPASSED', 'https://URLHERE');
    console.log(connection.SerialNumber);
  } catch (error) {
    console.error('Something went wrong:', error.message);
  }
}

// Call the async function to trigger the request
fetchAndLogSerialNumber();

为什么这样有效?

  • A Promise acts as a placeholder for the future result of an asynchronous operation. When the request finishes successfully, we use resolve() to pass the data out of the Promise. If something fails, we use reject() to pass the error.
  • .then() lets us run code once the Promise resolves, and .catch() handles any errors that occur.
  • async/await is syntactic sugar over Promises—it makes asynchronous code read like synchronous code, making it easier to follow and maintain.

内容的提问来源于stack exchange,提问作者John Hart

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 12:34:07