Skip to content

Instantly share code, notes, and snippets.

@josnidhin
Last active January 14, 2021 06:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josnidhin/d46900e20d21de6ce0763a542950ab65 to your computer and use it in GitHub Desktop.
Save josnidhin/d46900e20d21de6ce0763a542950ab65 to your computer and use it in GitHub Desktop.
Simple Nodejs http request without external dependencies
'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