This website is undergoing a re-design (Sat Jul 11 2020)

Make http/s requests with Node.js without any libraries

Gunar Gessner

Gunar Gessner

Jun 10, 2020

I was not able to use got on Firebase Functions. Apparently got uses a feature (async generators) that is only available on newer version of Node.js. This is the first time I have had a problem deploying serverless functions. It never happens on Vercel. But I had to use Firebase Functions because I needed to react to an event in a Firebase Database. Instead of playing whack-a-mole in trying to find a compatible library, I just wrote one that requires zero dependencies.

# POST JSON

const https = require("https");
async function post({ body, hostname, path }) {
  return new Promise((resolve, reject) => {
    const data = JSON.stringify(body);
    const options = {
      hostname,
      port: 443,
      path,
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Content-Length": data.length
      }
    };
    const req = https.request(options, res => {
      // console.log(`statusCode: ${res.statusCode}`);
      res.on("data", d => {
        // process.stdout.write(d)
      });
    });

    req.on("error", error => {
      console.error(error);
    });
    req.write(data);
    req.end();
    req.on("end", () => {
      resolve();
    });
  });
}