Skip to content

Instantly share code, notes, and snippets.

@kbrammer
Last active February 26, 2022 14:17
Show Gist options
  • Save kbrammer/232da2f6ee3087a507266458d503404a to your computer and use it in GitHub Desktop.
Save kbrammer/232da2f6ee3087a507266458d503404a to your computer and use it in GitHub Desktop.
node https get and post request as promise with optional JWT
const https = require("https");
// based on https://stackoverflow.com/questions/35182752/promises-with-http-get-node-js
module.exports = {
get(urlString, token = null) {
return new Promise((resolve, reject) => {
const url = new URL(urlString);
const requestOptions = {
method: "GET",
hostname: url.hostname,
path: url.pathname + url.search,
port: url.port,
headers: {
accept: "application/json",
},
};
if (token !== null) {
requestOptions.headers.Authorization = `Bearer ${token}`;
}
const req = https.request(requestOptions, (response) => {
let responseBody = "";
if (response.status >= 400) {
reject(
`Request to ${response.url} failed with HTTP ${response.status}`
);
}
response.setEncoding("utf8");
response.on("data", (chunk) => {
responseBody += chunk.toString();
});
response.on("end", () => resolve(responseBody));
});
req.on("error", (e) => {
reject(e);
});
req.end();
});
},
post(urlString, model, token = null) {
return new Promise((resolve, reject) => {
const url = new URL(urlString);
const postData = JSON.stringify(model);
const requestOptions = {
method: "POST",
hostname: url.hostname,
path: url.pathname + url.search,
port: url.port,
headers: {
accept: "application/json",
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(postData),
},
};
if (token !== null) {
requestOptions.headers.Authorization = `Bearer ${token}`;
}
const req = https.request(requestOptions, (response) => {
let responseBody = "";
if (response.status >= 400) {
reject(
`Request to ${response.url} failed with HTTP ${response.status}`
);
}
response.setEncoding("utf8");
response.on("data", (chunk) => {
responseBody += chunk.toString();
});
response.on("end", () => resolve(responseBody));
});
req.write(postData);
req.on("error", (e) => {
reject(e);
});
req.end();
});
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment