Node.js request directly to URL with options (http or https)

In order to get all components out of URL you need to parse it. Node v0.10.13 has stable module for it: url.parse

This is simple example how to do so:

var q = url.parse(urlStr, true);
var protocol = (q.protocol == "http") ? require('http') : require('https');
let options = {
    path:  q.pathname,
    host: q.hostname,
    port: q.port,
};
protocol.get(options, (res) => {...

For those ending up here, protocol includes :, and pathname does not include search so it must be added manually. Parameters shouldn't be parsed as they are not needed (so you can save computing time :)

Also it's not really a best practice to require inside a function and probably this code will end up inside a function so having all this improvements, so I would rewrite the answer to something like this:

import * as url from 'url';
import * as https from 'https';
import * as http from 'http';

const uri = url.parse(urlStr);
const { request } = uri.protocol === 'https:' ? https : http;
const opts = {
    headers, // Should be defined somewhere...
    method: 'GET',
    hostname: uri.hostname,
    port: uri.port,
    path: `${uri.pathname}${uri.search}`,
    protocol: uri.protocol,
};
const req = request(opts, (resp) => { ...