【问题标题】:Return https.get() response body to client with Nodejs使用 Nodejs 将 https.get() 响应正文返回给客户端
【发布时间】:2021-12-29 00:06:01
【问题描述】:

我正在尝试开发一个谷歌云功能,它将发出外部 https GET 请求并将响应正文返回给客户端。

流程:

  1. 客户端向 mockServer 函数发出请求
  2. 函数向 example.com 发出 GET 请求
  3. 函数将“结果”从 example.com 的响应正文返回到客户端

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); 成功记录结果,但我不知道如何将其返回给客户端。我还是新手并且正在学习,所以提前非常感谢您的帮助!

【问题讨论】:

  • 首先,您可以使用更简单的库来发出 API 请求。其次,您的 https 回调中的 res 正在掩盖来自 mockServer 的 res,您需要使用它来向客户端发送响应。
  • 谢谢,道格。我会尝试重命名。你有推荐的图书馆吗?我看到请求库已被弃用,因此不确定下一个最佳选择
  • axios, ky, node-fetch, 有很多
  • 谢谢你们!我和 axios 一起去了,它正在工作。我在上面添加了工作代码。
  • 注意:与其用解决方案更新您的问题,不如考虑回答您自己的问题并接受答案,让其他人知道您已经找到了解决方案。虽然回答您自己的问题可能看起来很奇怪,但这是 100% 允许的。

标签: javascript node.js google-cloud-functions


【解决方案1】:

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

感谢 cmets 中的@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
    })
  })

};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-22
    • 1970-01-01
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多