Tengo un script que requiere que use el módulo https del nodo en lugar de algo mejor. Estoy luchando por encontrar documentación que explique cómo funciona realmente https.request.
Veo muchos ejemplos, pero la forma en que se combinan estas funciones es bastante críptica para mí.
He puesto algunos comentarios en mi código a continuación para explicar las áreas que no entiendo.
Mi problema en este momento es que mi bloque catch no devuelve un error de la solicitud. Llega a esa condición pero la e está vacía. No estoy seguro de cómo manejar correctamente los errores aquí. Estoy aún más confundido por la necesidad de 3 condiciones diferentes que resultan en el rechazo de la promesa. ¿Cómo esta llamada a https tiene 3 formas de fallar? Tal vez mi código es simplemente incorrecto.
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(); }); };