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

NodeJS中HTTP POST请求返回access_token无法传递给调用函数的问题

解决returnToken函数返回undefined的问题

你的returnToken函数返回undefined是因为https.request是异步操作——函数在发起HTTP请求后会立即执行完毕,而请求的响应结果要等一段时间才会返回。你在res.on("end")回调里的return,只能给回调函数本身返回值,无法传递到外层的returnToken函数。

要正确返回异步操作的结果,需要用Promise封装整个请求逻辑,让returnToken返回一个Promise对象,之后通过.then()或async/await来获取结果。

修改后的代码

function returnToken() {
  return new Promise((resolve, reject) => {
    const https = require('follow-redirects').https;
    const qs = require('querystring');

    const options = {
      'method': 'POST',
      'hostname': hostname, // 确保该变量已提前定义
      'path': path, // 确保该变量已提前定义
      'headers': {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Cookie': 'AWSALBTG=VQeZ4MBoHfHiCgR7g4DBcvuSGVQgDKDPo95l9tiNlSv9WNmDW1Z6PqXjKOTP3LKeqkHw5//8vIH304VbApkBRePHFM8JVgOtmqpRpv9iVN+cYS73RiNl+kxWSnntRZQ4+oXnFkG5NVlZty+ohK8qyX1UhQDT5+UGhV9Kn9heLkbG; AWSALBTGCORS=VQeZ4MBoHfHiCgR7g4DBcvuSGVQgDKDPo95l9tiNlSv9WNmDW1Z6PqXjKOTP3LKeqkHw5//8vIH304VbApkBRePHFM8JVgOtmqpRpv9iVN+cYS73RiNl+kxWSnntRZQ4+oXnFkG5NVlZty+ohK8qyX1UhQDT5+UGhV9Kn9heLkbG'
      },
      'maxRedirects': 20
    };

    const req = https.request(options, function (res) {
      const chunks = [];

      res.on("data", function (chunk) {
        chunks.push(chunk);
      });

      res.on("end", function () {
        try {
          const body = Buffer.concat(chunks);
          const accessToken = JSON.parse(body).access_token;
          console.log(accessToken);
          resolve(accessToken); // 用resolve传递异步结果
        } catch (err) {
          reject(err); // 捕获JSON解析错误
        }
      });

      res.on("error", function (error) {
        reject(error);
      });
    });

    const postData = qs.stringify({
      'client_id': clientID, // 确保该变量已提前定义
      'client_secret': clientSecret, // 确保该变量已提前定义
      'scopes': scope, // 确保该变量已提前定义
      'grant_type': 'client_credentials'
    });

    req.write(postData);
    req.end();

    // 处理请求本身的网络错误
    req.on('error', (err) => {
      reject(err);
    });
  });
}

调用方式

方式1:使用.then()/.catch()

returnToken()
  .then(t => {
    console.log('t=' + t);
  })
  .catch(err => {
    console.error('获取token失败:', err);
  });

方式2:使用async/await(需在异步函数中调用)

async function getToken() {
  try {
    const t = await returnToken();
    console.log('t=' + t);
  } catch (err) {
    console.error('获取token失败:', err);
  }
}

getToken();

关键说明

  • 用Promise包裹异步请求逻辑,成功时通过resolve传递access_token,失败时通过reject传递错误信息。
  • 外层returnToken函数返回这个Promise对象,调用者可以通过异步方式获取结果。
  • 新增了对请求网络错误、JSON解析错误的捕获处理,避免程序意外崩溃。

内容的提问来源于stack exchange,提问作者Bert Wolf

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 05:35:21