Node HTTPS Request


Uncategorized

Updated Jan 29th, 2023

I typically send requests using Fetch or Axios but in using AWS Lambda I needed to send with Node’s built-in library, and more complicated, HTTPS module and request method.

so we listen for resp.on(“data”, () => {}) and resp.on(“end”, () => {})

The “on data” is a chunk of data has been received as the reponse is streamed back to us, a piece at a a time.

The “on end” is the whole response has been received and we want to parse it.

Always want to have an “on error” handler function

See the github gist here.

Need a callback that says, if res.statusCode == 200 then send a post request to my API.

Note: may also be interested in res.headers[“content-length”] to make sure the data isn’t too large like over a specific size in mb, ( 1185954 is 1.1 mb).

Shows a request within a request.

xample from geeks for geeks:

const https = require('https');

// Sample URL
const url = 'https://jsonplaceholder.typicode.com/todos/1';

const request = https.request(url, (response) => {
	let data = '';
	response.on('data', (chunk) => {
		data = data + chunk.toString();
	});

	response.on('end', () => {
		const body = JSON.parse(data);
		console.log(body);
	});
})

request.on('error', (error) => {
	console.log('An error', error);
});

request.end()

And from memberstack:

const https = require("https");

const options = {
  hostname: 'yourapi.com',
  port: 443,
  path: '/todos',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length
  }
}

https
  .request(options, resp => {
    // log the data
    resp.on("data", d => {
      process.stdout.write(d);
    });
  })
  .on("error", err => {
    console.log("Error: " + err.message);
  });

From chat GPT

const https = require('https');

function makeTwoHTTPSRequests() {
  https.get('https://cheesemynoodle.com/test1', (res) => {
    res.on('data', (data) => {
      const postData = data;

      const options = {
        hostname: 'cheesemynoodle.com',
        path: '/test2',
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
      };

      const req = https.request(options, (res) => {
        res.on('data', (data) => {
          console.log(`Response from second request: ${data}`);
        });
      });

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

makeTwoHTTPSRequests();

From Chat GPT-3 using Request Library

const request = require('request');

function makeTwoHTTPSRequests() {
  request.get('https://cheesemynoodle.com/test1', (error, response, body) => {
    const postData = body;

    request.post(
      {
        url: 'https://cheesemynoodle.com/test2',
        body: postData,
        json: true,
      },
      (error, response, body) => {
        console.log(`Response from second request: ${body}`);
      }
    );
  });
}

makeTwoHTTPSRequests();

Chat GPT-3 Node Fetch

const fetch = require('node-fetch');

async function makeTwoHTTPSRequests() {
  const response = await fetch('https://cheesemynoodle.com/test1');
  const postData = await response.json();

  const response2 = await fetch('https://cheesemynoodle.com/test2', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(postData),
  });

  const responseBody = await response2.json();
  console.log(`Response from second request: ${JSON.stringify(responseBody)}`);
}

makeTwoHTTPSRequests();

Slight Tweak on Above for AWS Lambda

const fetch = require('node-fetch');

exports.handler = async (event) => {
  const response = await fetch('https://cheesemynoodle.com/test1');
  const postData = await response.json();

  const response2 = await fetch('https://cheesemynoodle.com/test2', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(postData),
  });

  const responseBody = await response2.json();
  console.log(`Response from second request: ${JSON.stringify(responseBody)}`);

  return {
    statusCode: 200,
    body: JSON.stringify(responseBody),
  };
};

Sources

Docs here

Steve Griffith video here which shows pinging the NASA picture of the day API, needing an API.

Mosh has one here

Chaining requests with “request-promise” here