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

如何使用Promise等待Node.js的http POST请求执行完成并获取返回结果

代码修改方案

修改后完整代码

var http = require('http');
const auth = () => {
  // 把整个请求逻辑封装到Promise里
  return new Promise((resolve, reject) => {
    var post_data = JSON.stringify({
        "username": "aaa",
        "password": "bbb"
    });
    const options = { 
      // host去掉http://前缀,只保留IP地址
      host: '1.1.1.1',
      path: '/v1/authentication',
      method: 'POST',
      headers: {
          'Content-Type': 'application/json',
          'Content-Length': post_data.length
      }
    };

    const req = http.request(options, (res) => {
      res.setEncoding('utf8');
      var body = '';
      // 修正变量名,回调参数名和使用的变量名统一
      res.on('data', chunk => {
        body += chunk;
      });
      res.on('end', function() {
        console.log("Response body", body);
        // 请求成功返回响应体
        resolve(body);
      });
    });

    req.on('error', error => {
      console.error("error", error);
      // 请求失败返回错误
      reject(error);
    });

    req.write(post_data)
    req.end();
  })
};
exports.helloWorld = (req, res) => {
  let message = req.query.message || req.body.message || 'Hello World!';
  // 修正参数重名问题,避免覆盖外层的响应对象res
  auth().then((authResult)=>{
    res.status(200).send(authResult);
  }).catch(err => {
    // 增加错误捕获,避免请求失败时无响应
    res.status(500).send('请求失败:' + err.message);
  });
};

核心修改点

  • 把auth函数的请求逻辑完整封装在Promise实例中,请求成功时通过resolve返回响应结果,请求出错时通过reject抛出错误,实现异步等待逻辑
  • 修正options.host配置,移除多余的http://前缀,http模块的host参数仅需填写IP或域名,不需要携带协议头
  • 修正data事件回调的变量名错误,原代码回调参数定义为d,实际拼接用了未定义的chunk,统一改为chunk
  • 修正helloWorld函数中then回调的参数重名问题,避免内层res覆盖外层的响应对象res
  • 增加错误捕获逻辑,请求失败时返回500响应,避免请求异常时接口挂起

内容的提问来源于stack exchange,提问作者Bill Software Engineer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 19:06:03