Last active
June 20, 2017 12:38
-
-
Save iamso/30ffbf54e522eda559d46dc3fccc9888 to your computer and use it in GitHub Desktop.
Simple HTTP(S) request with Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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