Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

224
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda