Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

222
Vistas
Making an https.request with Node using promises

I have a script which requires me to use the node https module instead of something nicer. I am struggling to find documentation that explains how https.request really works.

I see plenty of examples but the way these functions are put together is rather cryptic to me.

I've put some comments in my code below to explain the areas that i do not understand.

My problem right now is my catch block isn't returning an error from the request. It gets to that condition but the e is empty. I am not sure how to properly handle errors here. I'm further confused by the need to 3 different conditions that result in reject of promise. How does this call to https have 3 ways to fail? Maybe my code is just wrong.

const https = require("https");

const payload = {
  username: "test",
  sendEmail: true,
};

callService(payload)
  .then((data) => {
    console.log(JSON.stringify(data));
  })
  .catch((e) => {
    console.log("This gives me nothing! does the reject not end up here? " + JSON.stringify(e));
  });

const callService = (payload) => {
  return new Promise((resolve, reject) => {
    const data = JSON.stringify(payload);
    const url = new URL(process.env.SERVICE_ENDPOINT);
    const options = {
      host: url.host,
      port: 443,
      path: url.pathname,
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Content-Length": data.length,
      },
    };
    const req = https.request(options, (res) => {
      if (res.statusCode < 200 || res.statusCode >= 300) {
        return reject(new Error("statusCode=" + res.statusCode)); 
        //so we did an Error class here but down below just reject(e), is that dumb?
      }

      //no idea wtf this is doing right here
      var body = [];
      res.on("data", function (chunk) {
        body.push(chunk);
      });

      //im turning the streamed data into a json object?
      res.on("end", function () {
        try {
          body = JSON.parse(Buffer.concat(body).toString());
        } catch (e) {
          //what would happen to trigger this error and where does it go?
          reject(e);
        }
        resolve(body); //yay?
      });
    });

    //wait we have to catch some other kind of error here? whats the difference between req and res?
    req.on("error", (e) => {
      reject(e.message);
    });

    req.write(data);
    req.end();
  });
};
about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda