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