Skip to content

Instantly share code, notes, and snippets.

@anshulrgoyal
Created December 26, 2018 10:27
Show Gist options
  • Select an option

  • Save anshulrgoyal/d3a6a183a6d06ed372b16b7467cdce77 to your computer and use it in GitHub Desktop.

Select an option

Save anshulrgoyal/d3a6a183a6d06ed372b16b7467cdce77 to your computer and use it in GitHub Desktop.
Make a request
const https = require('https');
const URL = require('url');
const queryString = require('querystring')
ajax = (url, options = {}, cb) => {
options = {
method: 'get',
body: null,
...options
}
const {method,body,headers} = options;
let bodyTobeSent = ""
let contentType = 'application/json'
if (body && 'json' in body) {
bodyTobeSent = JSON.parse(body.json);
contentType = 'application/json'
}
if (body && 'formdata' in body) {
bodyTobeSent = queryString.stringify(body.formdata);
contentType = 'application/x-www-form-urlencoded'
}
let responseData = "";
return new Promise((resolve, reject) => {
const parsedUrl = URL.parse(url, true);
const options = {
...parsedUrl,
method,
headers: { ...headers,
'user-agent': 'liblessserver',
'content-type': contentType,
'content-length': Buffer.byteLength(bodyTobeSent)
},
}
const req = https.request(options, (res) => {
res.on('data', (data) => {
responseData = responseData + data;
})
res.on('end', (data) => {
if (cb && typeof(cb) === 'function') {
cb(null, responseData)
} else {
resolve(responseData);
}
})
});
if(body&&('formdata' in body||'json' in body)){
req.write(bodyTobeSent);
}
req.on('error', (err) => {
if (cb && typeof(cb) === 'function') {
cb(err, null);
} else {
reject(err);
}
})
req.end()
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment