Пример #1
0
  return function (uri, options, done) {
    if (typeof uri === 'undefined') {
      throw new Error('undefined is not a valid uri or options object');
    }

    if (typeof options === 'function' && !done) {
      done = options;
    }

    if (options && typeof options === 'object') {
      options.uri = uri;
    } else if (typeof uri === 'string') {
      options = { uri: uri };
    } else {
      options = uri;
    }

    options = helpers.copy(options);

    if (done) {
      // Override request callback options to include additional parsing logic
      // and remove the third response body argument.
      options.callback = function (err, res) {
        if (res.req.method === 'HEAD') {
          return done(err, res);
        }

        var contentType = type(res.headers['content-type']);

        // Attempt to parse the response body as JSON.
        if (JSON_MIME_REGEXP.test(contentType) && res.body) {
          try {
            res.body = JSON.parse(res.body);
          } catch (e) {}
        }

        // Parse the response body as a url encoded string.
        if (QUERY_MIME_REGEXP.test(contentType) && res.body) {
          res.body = qs.parse(res.body);
        }

        return done(err, res);
      };
    }

    if (options.body && !isHost(options.body)) {
      var contentType;

      // Iterate over headers and find the content type.
      for (var key in options.headers) {
        if (key.toLowerCase() === 'content-type') {
          contentType = type(options.headers[key]);
          break;
        }
      }

      // Stringify the body as JSON.
      if (JSON_MIME_REGEXP.test(contentType)) {
        options.body = JSON.stringify(options.body);
      }

      // Stringify the body as a url encoded form.
      if (QUERY_MIME_REGEXP.test(contentType)) {
        options.body = qs.stringify(options.body);
      }
    }

    // Support multipart requests with `request`.
    if (options.body instanceof FormData) {
      options._form = options.body;

      delete options.body;
    }

    // Correct the request uri.
    options.uri = serverAddress(app, options.uri);

    return new request.Request(options);
  };
Пример #2
0
exports.agent = function (app, opts) {
  var options = opts ? helpers.copy(opts) : {};
  options.jar || (options.jar = request.jar());

  return exports(app).defaults(options);
};