Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

I am trying to develop a google cloud function that will make an external https GET request and return the response body to the client.

Flow:

  1. client makes request to mockServer function
  2. function makes GET request to example.com
  3. function returns "results" from response body from example.com to client

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()
};

I am able to successfully log the results with console.log("results:"+results); but I cannot figure out how to get it returned to the client. I am still new to this and am learning, so thank you so much in advance to any help!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Posting @YouthDev's solution as an answer:

Thanks to @DougStevenson and @Deko in the comments, I switched to an axios library and it works like a charm. Thank you to both for pointing me in the correct direction. Below is the working axios code.

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
    })
  })

};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!