Last active
January 14, 2021 06:50
-
-
Save josnidhin/d46900e20d21de6ce0763a542950ab65 to your computer and use it in GitHub Desktop.
Simple Nodejs http request without external dependencies
This file contains hidden or 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'), | |
HTTPS = require('https'), | |
PROTOCOL = { | |
HTTP: 'http:', | |
HTTPS: 'https:' | |
}; | |
function request (opts, data) { | |
return new Promise((resolve, reject) => requestPromise({resolve, reject, opts, data})); | |
} | |
function requestPromise({resolve, reject, opts, data}) { | |
const lib = opts.protocol === PROTOCOL.HTTPS ? HTTPS : HTTP, | |
req = lib.request(opts, (res) => { | |
if (res.statusCode < 200 || res.statusCode > 299) { | |
return reject(new Error(`Status code: ${res.statusCode}`)); | |
} | |
const body = []; | |
res.on('data', (chunk) => body.push(chunk)); | |
res.on('end', () => resolve(body.join(''))); | |
}); | |
req.on('error', reject); | |
if (data) { | |
req.write(data); | |
} | |
req.end(); | |
} | |
const data = JSON.stringify({ | |
name: "morpheus", | |
job: "leader" | |
}), | |
options = { | |
hostname: 'reqres.in', | |
port: 443, | |
protocol: PROTOCOL.HTTPS, | |
path: '/api/users', | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json', | |
'Content-Length': Buffer.byteLength(data) | |
} | |
}; | |
request(options, data) | |
.then(console.log) | |
.catch(console.log); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment