Skip to content

Instantly share code, notes, and snippets.

@Yengas
Last active March 18, 2021 01:03
Show Gist options
  • Save Yengas/e6c41e942569e137d0da038e79ae90f7 to your computer and use it in GitHub Desktop.
Save Yengas/e6c41e942569e137d0da038e79ae90f7 to your computer and use it in GitHub Desktop.
a simple promise returning request function for http and https get, post
const http = require("http");
const https = require("https");
function request(options) {
return new Promise((resolve, reject) => {
const { url, data, ...rest } = options;
const parsedURL = new URL(url);
const isHTTPS = parsedURL.protocol === "https:";
const lib = isHTTPS ? https : http;
const reqOptions = {
...rest,
...(data
? {
headers: { ...(rest.headers || {}), "Content-Length": data.length },
}
: {}),
};
const request = lib.request(url, reqOptions, (response) => {
if (response.statusCode < 200 || response.statusCode > 299) {
reject(
new Error("Failed to load page, status code: " + response.statusCode)
);
}
const body = [];
response.on("data", (chunk) => body.push(chunk));
response.on("end", () => resolve(body.join("")));
});
request.on("error", (err) => reject(err));
if (data) {
request.write(data);
}
request.end();
});
}

GET

await request({
  url: "https://postman-echo.com/get",
  method: "GET"
})

POST

await request({
  url: "https://postman-echo.com/post",
  method: "POST",
  data: JSON.stringify({ hello: 'world' }),
  headers: {
        "Content-Type": "application/json",
  },
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment