Skip to content

Instantly share code, notes, and snippets.

@muhammedmoussa1
Forked from ktheory/Readme.md
Created August 23, 2021 16:17
Show Gist options
  • Save muhammedmoussa1/5cd258fb10f66f3cf06f9b573b2d7370 to your computer and use it in GitHub Desktop.
Save muhammedmoussa1/5cd258fb10f66f3cf06f9b573b2d7370 to your computer and use it in GitHub Desktop.
Easily make HTTPS requests that return promises w/ nodejs

Javascript request yak shave

I wanted to easily make HTTP requests (both GET & POST) with a simple interface that returns promises.

The popular request & request-promises package are good, but I wanted to figure out how to do it w/out using external dependencies.

The key features are:

  • the ability to set a timeout
  • non-200 responses are considered errors that reject the promise.
  • any errors at the TCP socker/DNS level reject the promise.

Hat tip to webivore and the Node HTTP docs, whose learning curve I climbed.

It's great for AWS Lambda.

Examples

const url = require('url');
const req = require('httpPromise');
// Simple get request
req("https://httpbin.org/get")
  .then((res) => { console.log(res)})
  .catch((err) => { console.log("oh no: " + err)});

// Get req w/ timeout and extra headers:
req(Object.assign({}, url.parse("https://httpbin.org/get"), {timeout: 2000, headers: {'X-MyHeader': 'MyValue'}}))

// POST data:
req(Object.assign({}, url.parse("https://httpbin.org/post"), { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}}), "foo=bar")
  .then((res) => { console.log(res)})
  .catch((err) => { console.log("oh no: " + err)});
'use strict';
const https = require('https');
// Inspired from https://gist.github.com/ktheory/df3440b01d4b9d3197180d5254d7fb65
module.exports = ((urlOptions, data) => {
return new Promise((resolve, reject) => {
const req = https.request(urlOptions,
(res) => {
let body = '';
res.on('data', (chunk) => (body += chunk.toString()));
res.on('error', reject);
res.on('end', () => {
if (res.statusCode >= 200 && res.statusCode <= 299) {
resolve({statusCode: res.statusCode, headers: res.headers, body: body});
} else {
reject('Request failed. status: ' + res.statusCode + ', body: ' + body);
}
});
});
req.on('error', reject);
req.write(data, 'binary');
req.end();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment