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();
});
};