Created
December 26, 2018 10:27
-
-
Save anshulrgoyal/d3a6a183a6d06ed372b16b7467cdce77 to your computer and use it in GitHub Desktop.
Make a request
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
| 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