async function to make the proxied request (fires between brefore `pre` and `post` functions)
964855
function proxyReq (proxyObj, callback) {
  let proxyError = proxyObjErrors(proxyObj);
  if (proxyError) { return callback(new Error(proxyError)); }

  if (proxyObj.options.log) { logReqOpts(proxyObj.reqOpts); }

  // TESTING HELPER ONLY
  if (proxyObj.options.shortCircuit) { return callback(null, proxyObj); }

  // unless explicitly set, ignore encoding
  // THIS IS A HACK THAT MAY CAUSE ISSUES. I DON'T
  // KNOW OF AN IMMEDIATE WORKAROUND TO FIX IT.
  if (!proxyObj.options['accept-encoding']) {
    delete proxyObj.reqOpts.headers['accept-encoding'];
  }

  // Check for Form Post Parameters
  if (proxyObj.req.body && (proxyObj.reqOpts.method === 'POST' || proxyObj.reqOpts.method === 'PUT')) {
    proxyObj.reqOpts.form = proxyObj.req.body;
  }

  // make request
  request(proxyObj.reqOpts, function (error, response, body) {
    if (proxyObj.options.log) { logResponse(response, body); }

    // transfer result to resulting o
    proxyObj.res.set(helpers.defaultHeaders(proxyObj.options.response.headers, response ? response.headers : {}));

    proxyObj.result = {
      response : response,
      body     : body
    };

    return callback(error, proxyObj);
  });
}
738678
function requestPromisfied(options) {
  return new Promise(function (resolve, reject) {
    (0, _request2.default)(options, function (err, res) {
      if (err) {
        reject(err);
      }
      resolve(res.body);
    });
  });
}
1276319
function initApiProxy() {
  if (build.verbose)
    console.log('Proxying paths...');
  lodash.forEach(build.proxyMap, function (proxyOpts, urlPath) {
    if (build.verbose)
      console.log('  - url: "' + urlPath + '"');
    app.use(urlPath, proxy(proxyOpts));
    // e.g. `app.use('/api', proxy({target: "http://localhost:4321/api", 
    // changeOrigin: true});`
  });
}
507643
function proxyRequest(data, next) {

        debug('proxying %s %s', data.clientRequest.method, data.url);

        var middlewareHandledRequest = _.some(config.requestMiddleware, function(middleware) {
            middleware(data);
            return data.clientResponse.headersSent; // if true, then _.some will stop processing middleware here because we can no longer
        });

        if (!middlewareHandledRequest) {
            var uri = URL.parse(data.url);

            var options = {
                host: uri.hostname,
                port: uri.port,
                path: uri.path,
                method: data.clientRequest.method,
                headers: data.headers
            };

            //set the agent for the request.
            if(uri.protocol == 'http:' && config.httpAgent) {
              options.agent =  config.httpAgent;
            }
            if(uri.protocol == 'https:' && config.httpsAgent) {
              options.agent =  config.httpsAgent;
            }

            // what protocol to use for outgoing connections.
            var proto = (uri.protocol == 'https:') ? https : http;

            debug('sending remote request: ', options);

            data.remoteRequest = proto.request(options, function(remoteResponse) {
                data.remoteResponse = remoteResponse;
                data.remoteResponse.on('error', next);
                proxyResponse(data);
            });

            data.remoteRequest.on('error', next);

            // pass along POST data & let the remote server know when we're done sending data
            data.stream.pipe(data.remoteRequest);
        }

    }
925503
function _proxy(rule, metas) {
  var opts = _getRequestOpts(metas.req, rule);
  var request = httpsSyntax.test(rule.replace) ? httpsReq : httpReq;

  var pipe = request(opts, function (res) {
    res.headers.via = opts.headers.via;
    metas.res.writeHead(res.statusCode, res.headers);
    res.on('error', function (err) {
      metas.next(err);
    });
    res.pipe(metas.res);
  });

  pipe.on('error', function (err) {
    metas.next(err);
  });

  if(!metas.req.readable) {
    pipe.end();
  } else {
    metas.req.pipe(pipe);
  }
}
667934
function MakePSNRequest(method, url, fields, callback, token_fetch)
	{
		// use fields var as callback if it's missed out
		if (typeof fields == "function")
		{
			token_fetch = false;
			callback = fields;
			fields = {};
		}
		else if (typeof method == "function")
		{
			token_fetch = false;
			callback = method;
		}

		// parse stache fields in fields list
		for(var field_key in fields)
		{
			fields[field_key] = ParseStaches(fields[field_key]);
		}

		CheckTokens(function(error)
		{
			// check our tokens are fine
			if (!error)
			{
				// make PSN GET request
				URLGET(
					// parse URL for region etc.
					ParseStaches(url),
					fields,
					method,
					function(error, data)
					{
						if (error)
						{
							Log("PSN " + method + " Error: " + error);
							if (callback) callback(error);
							return;
						}

						if (data.error && (data.error.code === 2105858 || data.error.code === 2138626))
						{
							// access token has expired/failed/borked
							//  login again!
							Log("Access token failure, try to login again.");
							Login(function(error) {
								if (error)
								{
									if (callback) callback(error);
									return;
								}

								// call ourselves
								parent.Get(url, fields, callback, token_fetch);
							});
						}

						if (data.error && data.error.message)
						{
							// server error
							if (callback) callback(data.error.code + ": " + data.error.message, data.error);
							return;
						}

						// everything is fine! return data
						if (callback) callback(false, data);
					}
				);
			}
			else
			{
				Log("Token error: " + error);
				if (callback) callback(error);
				return;
			}
		}, token_fetch);
	}
381614
function proxyMethods(exec, query) {
    const methods = [].concat(END_POINT_METHODS).concat(CHAINABLE_METHODS);
    for (let name of methods) {
        const oldMethod = query[name];
        query[name] = function (...args) {
            const clonedQuery = query.clone();
            proxyMethods(exec, clonedQuery);
            oldMethod.apply(clonedQuery, args);
            if (CHAINABLE_METHODS.indexOf(name) > -1) {
                return clonedQuery;
            } else {
                return exec(clonedQuery.toString());
            }
        }
    }
}
11150
def _make_request_to_server(self, query_function, raise_for_status=True,
                                time_limit_seconds=2, retry_delay_seconds=0.2):
        
        start_time = datetime.datetime.now()
        while datetime.datetime.now() - start_time < datetime.timedelta(
                0, time_limit_seconds):
            error = None
            response = None
            try:
                response = query_function()
            except requests.exceptions.ConnectionError as e:
                error = ServerConnectionError(
                    "No response from server.\n%s" % e)
            except:
                if response:
                    logger.info(response.text)
                raise
            if response is not None and raise_for_status:
                # raises requests.exceptions.HTTPError
                self._raise_for_status(response)
            if error:
                time.sleep(retry_delay_seconds)
                continue
            else:
                return response
        raise error
234113
function createProxyHandler (proxies, urlRoot) {
  if (!proxies.length) {
    const nullProxy = (request, response, next) => next()
    nullProxy.upgrade = () => {}
    return nullProxy
  }

  function createProxy (request, response, next) {
    const proxyRecord = proxies.find((p) => request.url.startsWith(p.path))
    if (proxyRecord) {
      log.debug(`proxying request - ${request.url} to ${proxyRecord.host}:${proxyRecord.port}`)
      request.url = request.url.replace(proxyRecord.path, proxyRecord.baseUrl)
      proxyRecord.proxy.web(request, response)
    } else {
      return next()
    }
  }

  createProxy.upgrade = function (request, socket, head) {
    // special-case karma's route to avoid upgrading it
    if (request.url.startsWith(urlRoot)) {
      log.debug(`NOT upgrading proxyWebSocketRequest ${request.url}`)
      return
    }

    const proxyRecord = proxies.find((p) => request.url.startsWith(p.path))
    if (proxyRecord) {
      log.debug(`upgrade proxyWebSocketRequest ${request.url} to ${proxyRecord.host}:${proxyRecord.port}`)
      request.url = request.url.replace(proxyRecord.path, proxyRecord.baseUrl)
      proxyRecord.proxy.ws(request, socket, head)
    }
  }

  return createProxy
}
701896
async function _request (client, url, body, method, times = 1) {
  if (client.isDebug) {
    debug('Push URL :' + url)
    if (body) {
      debug('Body :' + body)
    }
    // debug("Auth :" + JSON.stringify(auth))
    debug('Method :' + method)
    debug('Times/MaxTryTimes : ' + times + '/' + client.maxTryTimes)
  }

  var options = {
    method: method.toUpperCase(),
    json: true,
    uri: url,
    body: body,
    auth: {
      user: client.appkey,
      pass: client.masterSecret
    },
    timeout: client.readTimeOut,
    proxy: client.proxy
  };

  try {
    return await Request(options);
  } catch (err) {
    if (err.error.code === 'ETIMEDOUT' && err.error.syscall !== 'connect') {
      // response timeout
      throw new JError.APIConnectionError(
        'Response timeout. Your request to the server may have already received, please check whether or not to push',
        true)
    } else if (err.error.code === 'ENOTFOUND') {
      // unknown host
      throw new JError.APIConnectionError('Unknown host : ' + url)
    } else if (times < client.maxTryTimes) {
      return _request(client, url, body, method, times + 1)
    } else {
      if (client.isDebug) {
        debug('Fail, HttpStatusCode: ' + err.statusCode + ' result: ' + JSON.stringify(err.error))
      }
      throw new JError.APIRequestError(err.statusCode, JSON.stringify(err.error))
    }
  }
}
324979
function makeRequest(url, handler) {
  const xhr = new XMLHttpRequest();

  xhr.open('GET', url, true);
  xhr.responseType = handler.type;

  xhr.onload = function onLoad(e) {
    if (this.status === 200 || this.status === 0) {
      handler.fn(null, xhr);
      return;
    }
    handler.fn(e, xhr);
  };
  xhr.onerror = function onError(e) {
    handler.fn(e, xhr);
  };
  xhr.send();
}
240290
function request(location, settings) {
    var cookie, data, options, proto, req;

    if (_.isUndefined(settings) && _.isObject(location)) {
        settings = location;
        location = settings.location;
    }

    if (_.isFunction(settings)) {
        settings = { complete: settings };
    }

    _.defaults(settings, {
        complete: function () {},
        headers: {},
        maxRedirects: 10,
        nRedirects: 0,
        timeout: 1000 * 10,  // timeout request after 10 seconds
        proxy: proxy         // default to global proxy object
    });

    _.defaults(settings.headers, {
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/24.0.1312.70 Safari/537.1', 
        'accept-encoding': 'gzip,deflate'
    });

    options = url.parse(location);
    _.extend(options, settings);

    if (settings.proxy) {                        
        if (options.protocol === 'https:') {
            // We must tunnel SSL over HTTP, simply setting proxy headers won't work
            options.agent = tunnel.httpsOverHttp({ 
                proxy: {
                    host: settings.proxy.host,
                    port: settings.proxy.port,
                    proxyAuth: settings.proxy.auth
                } 
            });                  
        } else {
            // Modify host and port to request via proxy
            options.host = settings.proxy.host;
            options.port = settings.proxy.port;
            options.path = options.href;
            options.headers['host'] = options.hostname;
            if (settings.proxy.auth) {            
                options.headers['proxy-authorization'] = 'Basic ' + new Buffer(settings.proxy.auth).toString('base64');
            }

            delete options.hostname;
            delete options.href;
            delete options.pathname;
        }
    }

    if (settings.cookieJar) {        
        cookie = settings.cookieJar.toString();
        if (cookie.length) {            
            options.headers['cookie'] = settings.cookieJar.toString();            
        }            
    }

    data = null;
    if (options.data) {
        data = options.data;

        if (!options.method) {
            options.method = 'POST'; // Default to POST when data present and method not supplied
        }
        
        if (_.isObject(options.data)) {
            if (_(options.headers['content-type']).startsWith('application/json')) {
                data = JSON.stringify(options.data);
            } else {            
                // Default to form encoding
                if (!options.headers['content-type']) {
                    options.headers['content-type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
                }
                data = querystring.stringify(options.data);
            }
        } else {
            // Send raw string...
            data = options.data;
        }  

        // Calculate content length
        options.headers['content-length'] = Buffer.byteLength(data);      
    }
    
    // switch between http/s depending on protocol  
    proto = (options.protocol === 'https:') ? https : http;
    req = proto.request(options, function (res) {
        var output = new StringStream();                
        switch (res.headers['content-encoding']) {
            case 'gzip':
                res.pipe(zlib.createGunzip()).pipe(output);
                break;
            case 'deflate':
                res.pipe(zlib.createInflate()).pipe(output);
                break;
            default:
                // Treat as uncompressed string
                res.pipe(output);
                break;
        }

        output.on('end', function() {
            var i, baseUrl, cookies, err, location;

            if (settings.cookieJar && res.headers['set-cookie']) {
                cookies = res.headers['set-cookie'];
                for (i = 0; i < cookies.length; i++) {
                    settings.cookieJar.set(cookies[i]);
                }
            }

            if (res.statusCode >= 300 && res.statusCode < 400) {
                if (settings.maxRedirects > settings.nRedirects++) {
                    // Follow redirect                                            
                    baseUrl = options.protocol + '//' + ((proxy) ? options.headers['host'] : options.host);
                    location = url.resolve(baseUrl, res.headers['location']);
                    request(location, settings);                                   
                } else {
                    err = new Error('Max redirects reached.');
                    err.success = false;
                    settings.complete(err); 
                }
            } else if (res.statusCode >= 400) {
                err = new Error(output.caught);
                err.success = false;
                err.code = res.statusCode;
                settings.complete(err);            
            } else {                                
                settings.complete(null, output.caught, res);
            }
        });
    });

    req.on('socket', function (socket) {
        socket.setTimeout(settings.timeout);
        socket.on('timeout', function() {
            req.abort();
        });
    });

    req.on('error', function (err) {
        err.success = false;
        settings.complete(err);
    });

    if (data) { req.write(data); }

    req.end();
}
109548
function onProxyError(proxy) {
  return (err, req, res) => {
    const host = req.headers && req.headers.host;
    console.log(
      chalk.red('Proxy error:') +
        ' Could not proxy request ' +
        chalk.cyan(req.url) +
        ' from ' +
        chalk.cyan(host) +
        ' to ' +
        chalk.cyan(proxy) +
        '.'
    );
    console.log(
      'See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (' +
        chalk.cyan(err.code) +
        ').'
    );
    console.log();

    // And immediately send the proper error response to the client.
    // Otherwise, the request will eventually timeout with ERR_EMPTY_RESPONSE on the client side.
    if (res.writeHead && !res.headersSent) {
      res.writeHead(500);
    }
    res.end(
      'Proxy error: Could not proxy request ' +
        req.url +
        ' from ' +
        host +
        ' to ' +
        proxy +
        ' (' +
        err.code +
        ').'
    );
  };
}
675358
def do_request(self, request, proxies, timeout, **_):
        """"""
        print('{0} {1}'.format(request.method, request.url))
        response = self.http.send(request, proxies=proxies, timeout=timeout,
                                  allow_redirects=False)
        response.raw = None  # Make pickleable
        return response
1321962
function createWorkerProxy(workersOrFunctions, opt_options) {
    var options = {
      // Automatically call the callback after a call if the return value is not
      // undefined.
      autoCallback: false,
      // Catch errors and automatically respond with an error callback. Off by
      // default since it breaks standard behavior.
      catchErrors: false,
      // A list of functions that can be called. This list will be used to make
      // the proxy functions available when Proxy is not supported. Note that
      // this is generally not needed since the worker will also publish its
      // known functions.
      functionNames: [],
      // Call console.time and console.timeEnd for calls sent though the proxy.
      timeCalls: false
    };

    if (opt_options) {
      for (var key in opt_options) {
        if (!(key in options)) continue;
        options[key] = opt_options[key];
      }
    }
    Object.freeze(options);

    // Ensure that we have an array of workers (even if only using one worker).
    if (typeof Worker != 'undefined' && (workersOrFunctions instanceof Worker)) {
      workersOrFunctions = [workersOrFunctions];
    }

    if (Array.isArray(workersOrFunctions)) {
      return sendCallsToWorker(workersOrFunctions, options);
    } else {
      receiveCallsFromOwner(workersOrFunctions, options);
    }
  }
408311
function makePostCorsRequest (url, data) {
        var xhr = createCORSRequest('POST', url, data);

        if (typeof _beforeXHRCallback === 'function') {
            _beforeXHRCallback(xhr);
        }

        if ('withCredentials' in xhr) {

            xhr.onreadystatechange = function() {
                if (xhr.readyState !== 4) {
                    return;
                }

                if (xhr.status === 202) {
                    sendSavedErrors();
                } else if (_enableOfflineSave && xhr.status !== 403 && xhr.status !== 400 && xhr.status !== 429) {
                    offlineSave(url, data);
                }
            };

            xhr.onload = function() {
                _private.log('posted to Raygun');

                callAfterSend(this);
            };

        } else if (window.XDomainRequest) {
            xhr.ontimeout = function() {
                if (_enableOfflineSave) {
                    _private.log('Raygun: saved locally');
                    offlineSave(url, data);
                }
            };

            xhr.onload = function() {
                _private.log('posted to Raygun');

                sendSavedErrors();
                callAfterSend(this);
            };
        }

        xhr.onerror = function() {
            _private.log('failed to post to Raygun');

            callAfterSend(this);
        };

        if (!xhr) {
            _private.log('CORS not supported');
            return;
        }

        xhr.send(data);
    }
230451
function makeHttpRequest(next) {
  var start = Date.now();

  var timestamp = Date.now();
  var reqBody = 'time * 2 = ' + (timestamp * 2);

  sepia.filter({
    url: /.*/,
    urlFilter: function(url) {
      // disregard the timestamp in the query parameter
      return url.replace(/time\=[0-9]+/, '');
    },
    bodyFilter: function(body) {
      // disregard the timestamp in the request body
      return body.replace(/\= [0-9]+/, '');
    }
  });

  request({
    url: 'http://localhost:1337',
    method: 'POST',
    qs: {
      time: timestamp
    },
    body: reqBody
  }, function(err, data, body) {
    var time = Date.now() - start;

    console.log('FILTERS');
    console.log('  status:', data.statusCode);
    console.log('  body  :', body);
    console.log('  time  :', time);

    common.verify(function() {
      common.shouldBeDynamicallyTimed(time);
    });

    console.log();

    next();
  });
}