Skip to content

Instantly share code, notes, and snippets.

@iamso
Last active June 20, 2017 12:38
Show Gist options
  • Save iamso/30ffbf54e522eda559d46dc3fccc9888 to your computer and use it in GitHub Desktop.
Save iamso/30ffbf54e522eda559d46dc3fccc9888 to your computer and use it in GitHub Desktop.
Simple HTTP(S) request with Node.js
'use strict';
const http = require('http');
const https = require('https');
const {URL} = require('url');
const methods = {};
['get', 'post', 'put', 'patch', 'delete', 'head', 'options'].forEach(method => {
methods[method] = (url, data, headers) => {
return request(url, method, data, headers);
};
});
function request(url = '', method = 'get', data = '', headers = {}) {
return new Promise((resolve, reject) => {
url = new URL(url);
const options = {
host: url.host,
port: url.port || url.protocol === 'http:' ? 80 : 443,
path: url.pathname,
method: method.toUpperCase(),
headers: Object.assign({
'Accept': 'application/json',
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(data = data ? JSON.stringify(data) : ''),
}, headers),
};
const req = (url.protocol === 'http:' ? http : https).request(options, res => {
let body = '';
res.setEncoding('utf8');
res.on('data', chunk => {
body += chunk;
});
res.on('end', () => {
let data;
try {
data = JSON.parse(body);
}
catch(e) {
data = body;
};
resolve(data);
});
}).on('error', error => {
reject(error);
});
req.write(data);
req.end();
});
}
module.exports = methods;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment