Skip to content

Instantly share code, notes, and snippets.

@orhanveli
Created November 26, 2019 17:16
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 orhanveli/813323e929b8214e8a5b41c3f4a96672 to your computer and use it in GitHub Desktop.
Save orhanveli/813323e929b8214e8a5b41c3f4a96672 to your computer and use it in GitHub Desktop.
make req with http module
export const makeReq = (url: string | undefined, data = '', headers: any = {}, timeout = 5000): Promise<string> => {
if (!url) {
throw 'url must be defined!';
}
const contentLength = Buffer.byteLength(data, 'utf-8');
headers['Content-Length'] = contentLength;
headers['Content-Type'] = 'text/xml; charset=utf-8';
headers['Connection'] = 'keep-alive';
const uri = new URL(url);
const options: http.RequestOptions = {
hostname: uri.hostname,
host: uri.hostname,
port: uri.port,
path: uri.pathname,
method: 'POST',
headers,
// rejectUnauthorized: false,
timeout,
};
return new Promise((resolve, reject): void => {
const response: string[] = [];
const decoder = new StringDecoder('utf8');
if (options.headers && lastCookies.length > 0) {
options.headers['Cookie'] = lastCookies.map(c=>c.substr(0, c.indexOf(';'))).reduce((a, b) => a + '; ' + b);
}
const executer = (options: any, cb: (response: http.IncomingMessage) => void) => {
const req = http.request(options, (res) => {
if (req.aborted) return reject('aborted');
cb(res);
});
req.on('error', (err) => reject(err));
req.write(Buffer.from(data));
req.end();
};
const reqCallback = (res: http.IncomingMessage) => {
res.on('data', (chunk) => {
const str = decoder.write(chunk);
response.push(str);
// resolve(chunk.toString("utf8"));
});
res.on('end', () => {
decoder.end();
resolve(response.join(''));
});
res.on('error', (err) => reject(err));
};
executer(options, reqCallback);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment