Return https.get() 使用 Nodejs 对客户端的响应正文

Return https.get() response body to client with Nodejs

我正在尝试开发一个 google 云函数,它将向客户端发出外部 https GET 请求和 return 响应主体。

流量:

  1. 客户端向 mockServer 函数发出请求
  2. 函数向 example.com
  3. 发出 GET 请求
  4. 函数return从example.com到客户端
  5. 的响应主体的“结果”

exports.mockServer = (req, res) => {
    'use strict';
    var https = require('https');
    
    var options = {
        host: 'example.com',
      path: '/path',
      headers: {
        'accept': 'application/json',
        'X-API-Key': 'XXXX'
      }
    };

if (req.method == 'GET'){
https.get(options, function (res) {
        var data = '';
        res.on('data', function (chunk) {
            data += chunk;
        });
        res.on('end', function () {
            if (res.statusCode === 200) {
                  var res_body = JSON.parse(data);
                  var results = JSON.stringify(res_body.result)
                    console.log("results:"+results);
            } else {
                console.log('Status:', res.statusCode);
            }
        });
    }).on('error', function (err) {
          console.log('Error:', err);
    });

} else {
  console.log("Wrong Method");
}   
  res.end()
};

我可以使用 console.log("results:"+results); 成功记录结果,但我不知道如何将它 return 发送给客户端。我对此还很陌生,正在学习,所以非常感谢您的帮助!

发布@YouthDev 的解决方案作为答案:

感谢评论中的@DougStevenson 和@Deko,我切换到 axios library 并且效果很好。感谢你们为我指明了正确的方向。下面是工作的 axios 代码。

exports.mockServer = (req, res) => {
  const axios = require('axios').create({
    baseURL: 'https://example.com'
  });
  return axios.get('/path',{ headers: {'accept': 'application/json','X-API-Key': 'XXXXXX'} })
  .then(response => {
    console.log(response.data);
    return res.status(200).json({
      message: response.data
    })
  })
  .catch(err => {
    return res.status(500).json({
      error: err
    })
  })

};