title: Making an https.request with Node using promises
body: <p>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.</p>
  <p>I see plenty of examples but the way these functions are put together is rather cryptic to me.</p>
  <p>I've put some comments in my code below to explain the areas that i do not understand.</p>
  <p>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.</p>
  <pre><code>const https = require(&quot;https&quot;);
  
  const payload = {
    username: &quot;test&quot;,
    sendEmail: true,
  };
  
  callService(payload)
    .then((data) =&gt; {
      console.log(JSON.stringify(data));
    })
    .catch((e) =&gt; {
      console.log(&quot;This gives me nothing! does the reject not end up here? &quot; + JSON.stringify(e));
    });
  
  const callService = (payload) =&gt; {
    return new Promise((resolve, reject) =&gt; {
      const data = JSON.stringify(payload);
      const url = new URL(process.env.SERVICE_ENDPOINT);
      const options = {
        host: url.host,
        port: 443,
        path: url.pathname,
        method: &quot;POST&quot;,
        headers: {
          &quot;Content-Type&quot;: &quot;application/json&quot;,
          &quot;Content-Length&quot;: data.length,
        },
      };
      const req = https.request(options, (res) =&gt; {
        if (res.statusCode &lt; 200 || res.statusCode &gt;= 300) {
          return reject(new Error(&quot;statusCode=&quot; + 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(&quot;data&quot;, function (chunk) {
          body.push(chunk);
        });
  
        //im turning the streamed data into a json object?
        res.on(&quot;end&quot;, 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(&quot;error&quot;, (e) =&gt; {
        reject(e.message);
      });
  
      req.write(data);
      req.end();
    });
  };
  </code></pre>