GithubHelp home page GithubHelp logo

request / request-promise Goto Github PK

View Code? Open in Web Editor NEW
4.8K 4.8K 297.0 300 KB

The simplified HTTP request client 'request' with Promise support. Powered by Bluebird.

License: ISC License

JavaScript 100.00%

request-promise's Introduction

Deprecated!

As of Feb 11th 2020, request is fully deprecated. No new changes are expected to land. In fact, none have landed for some time.

For more information about why request is deprecated and possible alternatives refer to this issue.

Request - Simplified HTTP client

npm package

Build status Coverage Coverage Dependency Status Known Vulnerabilities Gitter

Super simple to use

Request is designed to be the simplest way possible to make http calls. It supports HTTPS and follows redirects by default.

const request = require('request');
request('http://www.google.com', function (error, response, body) {
  console.error('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Print the HTML for the Google homepage.
});

Table of contents

Request also offers convenience methods like request.defaults and request.post, and there are lots of usage examples and several debugging techniques.


Streaming

You can stream any response to a file stream.

request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))

You can also stream a file to a PUT or POST request. This method will also check the file extension against a mapping of file extensions to content-types (in this case application/json) and use the proper content-type in the PUT request (if the headers don’t already provide one).

fs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json'))

Request can also pipe to itself. When doing so, content-type and content-length are preserved in the PUT headers.

request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png'))

Request emits a "response" event when a response is received. The response argument will be an instance of http.IncomingMessage.

request
  .get('http://google.com/img.png')
  .on('response', function(response) {
    console.log(response.statusCode) // 200
    console.log(response.headers['content-type']) // 'image/png'
  })
  .pipe(request.put('http://mysite.com/img.png'))

To easily handle errors when streaming requests, listen to the error event before piping:

request
  .get('http://mysite.com/doodle.png')
  .on('error', function(err) {
    console.error(err)
  })
  .pipe(fs.createWriteStream('doodle.png'))

Now let’s get fancy.

http.createServer(function (req, resp) {
  if (req.url === '/doodle.png') {
    if (req.method === 'PUT') {
      req.pipe(request.put('http://mysite.com/doodle.png'))
    } else if (req.method === 'GET' || req.method === 'HEAD') {
      request.get('http://mysite.com/doodle.png').pipe(resp)
    }
  }
})

You can also pipe() from http.ServerRequest instances, as well as to http.ServerResponse instances. The HTTP method, headers, and entity-body data will be sent. Which means that, if you don't really care about security, you can do:

http.createServer(function (req, resp) {
  if (req.url === '/doodle.png') {
    const x = request('http://mysite.com/doodle.png')
    req.pipe(x)
    x.pipe(resp)
  }
})

And since pipe() returns the destination stream in ≥ Node 0.5.x you can do one line proxying. :)

req.pipe(request('http://mysite.com/doodle.png')).pipe(resp)

Also, none of this new functionality conflicts with requests previous features, it just expands them.

const r = request.defaults({'proxy':'http://localproxy.com'})

http.createServer(function (req, resp) {
  if (req.url === '/doodle.png') {
    r.get('http://google.com/doodle.png').pipe(resp)
  }
})

You can still use intermediate proxies, the requests will still follow HTTP forwards, etc.

back to top


Promises & Async/Await

request supports both streaming and callback interfaces natively. If you'd like request to return a Promise instead, you can use an alternative interface wrapper for request. These wrappers can be useful if you prefer to work with Promises, or if you'd like to use async/await in ES2017.

Several alternative interfaces are provided by the request team, including:

Also, util.promisify, which is available from Node.js v8.0 can be used to convert a regular function that takes a callback to return a promise instead.

back to top


Forms

request supports application/x-www-form-urlencoded and multipart/form-data form uploads. For multipart/related refer to the multipart API.

application/x-www-form-urlencoded (URL-Encoded Forms)

URL-encoded forms are simple.

request.post('http://service.com/upload', {form:{key:'value'}})
// or
request.post('http://service.com/upload').form({key:'value'})
// or
request.post({url:'http://service.com/upload', form: {key:'value'}}, function(err,httpResponse,body){ /* ... */ })

multipart/form-data (Multipart Form Uploads)

For multipart/form-data we use the form-data library by @felixge. For the most cases, you can pass your upload form data via the formData option.

const formData = {
  // Pass a simple key-value pair
  my_field: 'my_value',
  // Pass data via Buffers
  my_buffer: Buffer.from([1, 2, 3]),
  // Pass data via Streams
  my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
  // Pass multiple values /w an Array
  attachments: [
    fs.createReadStream(__dirname + '/attachment1.jpg'),
    fs.createReadStream(__dirname + '/attachment2.jpg')
  ],
  // Pass optional meta-data with an 'options' object with style: {value: DATA, options: OPTIONS}
  // Use case: for some types of streams, you'll need to provide "file"-related information manually.
  // See the `form-data` README for more information about options: https://github.com/form-data/form-data
  custom_file: {
    value:  fs.createReadStream('/dev/urandom'),
    options: {
      filename: 'topsecret.jpg',
      contentType: 'image/jpeg'
    }
  }
};
request.post({url:'http://service.com/upload', formData: formData}, function optionalCallback(err, httpResponse, body) {
  if (err) {
    return console.error('upload failed:', err);
  }
  console.log('Upload successful!  Server responded with:', body);
});

For advanced cases, you can access the form-data object itself via r.form(). This can be modified until the request is fired on the next cycle of the event-loop. (Note that this calling form() will clear the currently set form data for that request.)

// NOTE: Advanced use-case, for normal use see 'formData' usage above
const r = request.post('http://service.com/upload', function optionalCallback(err, httpResponse, body) {...})
const form = r.form();
form.append('my_field', 'my_value');
form.append('my_buffer', Buffer.from([1, 2, 3]));
form.append('custom_file', fs.createReadStream(__dirname + '/unicycle.jpg'), {filename: 'unicycle.jpg'});

See the form-data README for more information & examples.

multipart/related

Some variations in different HTTP implementations require a newline/CRLF before, after, or both before and after the boundary of a multipart/related request (using the multipart option). This has been observed in the .NET WebAPI version 4.0. You can turn on a boundary preambleCRLF or postamble by passing them as true to your request options.

  request({
    method: 'PUT',
    preambleCRLF: true,
    postambleCRLF: true,
    uri: 'http://service.com/upload',
    multipart: [
      {
        'content-type': 'application/json',
        body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})
      },
      { body: 'I am an attachment' },
      { body: fs.createReadStream('image.png') }
    ],
    // alternatively pass an object containing additional options
    multipart: {
      chunked: false,
      data: [
        {
          'content-type': 'application/json',
          body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})
        },
        { body: 'I am an attachment' }
      ]
    }
  },
  function (error, response, body) {
    if (error) {
      return console.error('upload failed:', error);
    }
    console.log('Upload successful!  Server responded with:', body);
  })

back to top


HTTP Authentication

request.get('http://some.server.com/').auth('username', 'password', false);
// or
request.get('http://some.server.com/', {
  'auth': {
    'user': 'username',
    'pass': 'password',
    'sendImmediately': false
  }
});
// or
request.get('http://some.server.com/').auth(null, null, true, 'bearerToken');
// or
request.get('http://some.server.com/', {
  'auth': {
    'bearer': 'bearerToken'
  }
});

If passed as an option, auth should be a hash containing values:

  • user || username
  • pass || password
  • sendImmediately (optional)
  • bearer (optional)

The method form takes parameters auth(username, password, sendImmediately, bearer).

sendImmediately defaults to true, which causes a basic or bearer authentication header to be sent. If sendImmediately is false, then request will retry with a proper authentication header after receiving a 401 response from the server (which must contain a WWW-Authenticate header indicating the required authentication method).

Note that you can also specify basic authentication using the URL itself, as detailed in RFC 1738. Simply pass the user:password before the host with an @ sign:

const username = 'username',
    password = 'password',
    url = 'http://' + username + ':' + password + '@some.server.com';

request({url}, function (error, response, body) {
   // Do more stuff with 'body' here
});

Digest authentication is supported, but it only works with sendImmediately set to false; otherwise request will send basic authentication on the initial request, which will probably cause the request to fail.

Bearer authentication is supported, and is activated when the bearer value is available. The value may be either a String or a Function returning a String. Using a function to supply the bearer token is particularly useful if used in conjunction with defaults to allow a single function to supply the last known token at the time of sending a request, or to compute one on the fly.

back to top


Custom HTTP Headers

HTTP Headers, such as User-Agent, can be set in the options object. In the example below, we call the github API to find out the number of stars and forks for the request repository. This requires a custom User-Agent header as well as https.

const request = require('request');

const options = {
  url: 'https://api.github.com/repos/request/request',
  headers: {
    'User-Agent': 'request'
  }
};

function callback(error, response, body) {
  if (!error && response.statusCode == 200) {
    const info = JSON.parse(body);
    console.log(info.stargazers_count + " Stars");
    console.log(info.forks_count + " Forks");
  }
}

request(options, callback);

back to top


OAuth Signing

OAuth version 1.0 is supported. The default signing algorithm is HMAC-SHA1:

// OAuth1.0 - 3-legged server side flow (Twitter example)
// step 1
const qs = require('querystring')
  , oauth =
    { callback: 'http://mysite.com/callback/'
    , consumer_key: CONSUMER_KEY
    , consumer_secret: CONSUMER_SECRET
    }
  , url = 'https://api.twitter.com/oauth/request_token'
  ;
request.post({url:url, oauth:oauth}, function (e, r, body) {
  // Ideally, you would take the body in the response
  // and construct a URL that a user clicks on (like a sign in button).
  // The verifier is only available in the response after a user has
  // verified with twitter that they are authorizing your app.

  // step 2
  const req_data = qs.parse(body)
  const uri = 'https://api.twitter.com/oauth/authenticate'
    + '?' + qs.stringify({oauth_token: req_data.oauth_token})
  // redirect the user to the authorize uri

  // step 3
  // after the user is redirected back to your server
  const auth_data = qs.parse(body)
    , oauth =
      { consumer_key: CONSUMER_KEY
      , consumer_secret: CONSUMER_SECRET
      , token: auth_data.oauth_token
      , token_secret: req_data.oauth_token_secret
      , verifier: auth_data.oauth_verifier
      }
    , url = 'https://api.twitter.com/oauth/access_token'
    ;
  request.post({url:url, oauth:oauth}, function (e, r, body) {
    // ready to make signed requests on behalf of the user
    const perm_data = qs.parse(body)
      , oauth =
        { consumer_key: CONSUMER_KEY
        , consumer_secret: CONSUMER_SECRET
        , token: perm_data.oauth_token
        , token_secret: perm_data.oauth_token_secret
        }
      , url = 'https://api.twitter.com/1.1/users/show.json'
      , qs =
        { screen_name: perm_data.screen_name
        , user_id: perm_data.user_id
        }
      ;
    request.get({url:url, oauth:oauth, qs:qs, json:true}, function (e, r, user) {
      console.log(user)
    })
  })
})

For RSA-SHA1 signing, make the following changes to the OAuth options object:

  • Pass signature_method : 'RSA-SHA1'
  • Instead of consumer_secret, specify a private_key string in PEM format

For PLAINTEXT signing, make the following changes to the OAuth options object:

  • Pass signature_method : 'PLAINTEXT'

To send OAuth parameters via query params or in a post body as described in The Consumer Request Parameters section of the oauth1 spec:

  • Pass transport_method : 'query' or transport_method : 'body' in the OAuth options object.
  • transport_method defaults to 'header'

To use Request Body Hash you can either

  • Manually generate the body hash and pass it as a string body_hash: '...'
  • Automatically generate the body hash by passing body_hash: true

back to top


Proxies

If you specify a proxy option, then the request (and any subsequent redirects) will be sent via a connection to the proxy server.

If your endpoint is an https url, and you are using a proxy, then request will send a CONNECT request to the proxy server first, and then use the supplied connection to connect to the endpoint.

That is, first it will make a request like:

HTTP/1.1 CONNECT endpoint-server.com:80
Host: proxy-server.com
User-Agent: whatever user agent you specify

and then the proxy server make a TCP connection to endpoint-server on port 80, and return a response that looks like:

HTTP/1.1 200 OK

At this point, the connection is left open, and the client is communicating directly with the endpoint-server.com machine.

See the wikipedia page on HTTP Tunneling for more information.

By default, when proxying http traffic, request will simply make a standard proxied http request. This is done by making the url section of the initial line of the request a fully qualified url to the endpoint.

For example, it will make a single request that looks like:

HTTP/1.1 GET http://endpoint-server.com/some-url
Host: proxy-server.com
Other-Headers: all go here

request body or whatever

Because a pure "http over http" tunnel offers no additional security or other features, it is generally simpler to go with a straightforward HTTP proxy in this case. However, if you would like to force a tunneling proxy, you may set the tunnel option to true.

You can also make a standard proxied http request by explicitly setting tunnel : false, but note that this will allow the proxy to see the traffic to/from the destination server.

If you are using a tunneling proxy, you may set the proxyHeaderWhiteList to share certain headers with the proxy.

You can also set the proxyHeaderExclusiveList to share certain headers only with the proxy and not with destination host.

By default, this set is:

accept
accept-charset
accept-encoding
accept-language
accept-ranges
cache-control
content-encoding
content-language
content-length
content-location
content-md5
content-range
content-type
connection
date
expect
max-forwards
pragma
proxy-authorization
referer
te
transfer-encoding
user-agent
via

Note that, when using a tunneling proxy, the proxy-authorization header and any headers from custom proxyHeaderExclusiveList are never sent to the endpoint server, but only to the proxy server.

Controlling proxy behaviour using environment variables

The following environment variables are respected by request:

  • HTTP_PROXY / http_proxy
  • HTTPS_PROXY / https_proxy
  • NO_PROXY / no_proxy

When HTTP_PROXY / http_proxy are set, they will be used to proxy non-SSL requests that do not have an explicit proxy configuration option present. Similarly, HTTPS_PROXY / https_proxy will be respected for SSL requests that do not have an explicit proxy configuration option. It is valid to define a proxy in one of the environment variables, but then override it for a specific request, using the proxy configuration option. Furthermore, the proxy configuration option can be explicitly set to false / null to opt out of proxying altogether for that request.

request is also aware of the NO_PROXY/no_proxy environment variables. These variables provide a granular way to opt out of proxying, on a per-host basis. It should contain a comma separated list of hosts to opt out of proxying. It is also possible to opt of proxying when a particular destination port is used. Finally, the variable may be set to * to opt out of the implicit proxy configuration of the other environment variables.

Here's some examples of valid no_proxy values:

  • google.com - don't proxy HTTP/HTTPS requests to Google.
  • google.com:443 - don't proxy HTTPS requests to Google, but do proxy HTTP requests to Google.
  • google.com:443, yahoo.com:80 - don't proxy HTTPS requests to Google, and don't proxy HTTP requests to Yahoo!
  • * - ignore https_proxy/http_proxy environment variables altogether.

back to top


UNIX Domain Sockets

request supports making requests to UNIX Domain Sockets. To make one, use the following URL scheme:

/* Pattern */ 'http://unix:SOCKET:PATH'
/* Example */ request.get('http://unix:/absolute/path/to/unix.socket:/request/path')

Note: The SOCKET path is assumed to be absolute to the root of the host file system.

back to top


TLS/SSL Protocol

TLS/SSL Protocol options, such as cert, key and passphrase, can be set directly in options object, in the agentOptions property of the options object, or even in https.globalAgent.options. Keep in mind that, although agentOptions allows for a slightly wider range of configurations, the recommended way is via options object directly, as using agentOptions or https.globalAgent.options would not be applied in the same way in proxied environments (as data travels through a TLS connection instead of an http/https agent).

const fs = require('fs')
    , path = require('path')
    , certFile = path.resolve(__dirname, 'ssl/client.crt')
    , keyFile = path.resolve(__dirname, 'ssl/client.key')
    , caFile = path.resolve(__dirname, 'ssl/ca.cert.pem')
    , request = require('request');

const options = {
    url: 'https://api.some-server.com/',
    cert: fs.readFileSync(certFile),
    key: fs.readFileSync(keyFile),
    passphrase: 'password',
    ca: fs.readFileSync(caFile)
};

request.get(options);

Using options.agentOptions

In the example below, we call an API that requires client side SSL certificate (in PEM format) with passphrase protected private key (in PEM format) and disable the SSLv3 protocol:

const fs = require('fs')
    , path = require('path')
    , certFile = path.resolve(__dirname, 'ssl/client.crt')
    , keyFile = path.resolve(__dirname, 'ssl/client.key')
    , request = require('request');

const options = {
    url: 'https://api.some-server.com/',
    agentOptions: {
        cert: fs.readFileSync(certFile),
        key: fs.readFileSync(keyFile),
        // Or use `pfx` property replacing `cert` and `key` when using private key, certificate and CA certs in PFX or PKCS12 format:
        // pfx: fs.readFileSync(pfxFilePath),
        passphrase: 'password',
        securityOptions: 'SSL_OP_NO_SSLv3'
    }
};

request.get(options);

It is able to force using SSLv3 only by specifying secureProtocol:

request.get({
    url: 'https://api.some-server.com/',
    agentOptions: {
        secureProtocol: 'SSLv3_method'
    }
});

It is possible to accept other certificates than those signed by generally allowed Certificate Authorities (CAs). This can be useful, for example, when using self-signed certificates. To require a different root certificate, you can specify the signing CA by adding the contents of the CA's certificate file to the agentOptions. The certificate the domain presents must be signed by the root certificate specified:

request.get({
    url: 'https://api.some-server.com/',
    agentOptions: {
        ca: fs.readFileSync('ca.cert.pem')
    }
});

The ca value can be an array of certificates, in the event you have a private or internal corporate public-key infrastructure hierarchy. For example, if you want to connect to https://api.some-server.com which presents a key chain consisting of:

  1. its own public key, which is signed by:
  2. an intermediate "Corp Issuing Server", that is in turn signed by:
  3. a root CA "Corp Root CA";

you can configure your request as follows:

request.get({
    url: 'https://api.some-server.com/',
    agentOptions: {
        ca: [
          fs.readFileSync('Corp Issuing Server.pem'),
          fs.readFileSync('Corp Root CA.pem')
        ]
    }
});

back to top


Support for HAR 1.2

The options.har property will override the values: url, method, qs, headers, form, formData, body, json, as well as construct multipart data and read files from disk when request.postData.params[].fileName is present without a matching value.

A validation step will check if the HAR Request format matches the latest spec (v1.2) and will skip parsing if not matching.

  const request = require('request')
  request({
    // will be ignored
    method: 'GET',
    uri: 'http://www.google.com',

    // HTTP Archive Request Object
    har: {
      url: 'http://www.mockbin.com/har',
      method: 'POST',
      headers: [
        {
          name: 'content-type',
          value: 'application/x-www-form-urlencoded'
        }
      ],
      postData: {
        mimeType: 'application/x-www-form-urlencoded',
        params: [
          {
            name: 'foo',
            value: 'bar'
          },
          {
            name: 'hello',
            value: 'world'
          }
        ]
      }
    }
  })

  // a POST request will be sent to http://www.mockbin.com
  // with body an application/x-www-form-urlencoded body:
  // foo=bar&hello=world

back to top


request(options, callback)

The first argument can be either a url or an options object. The only required option is uri; all others are optional.

  • uri || url - fully qualified uri or a parsed url object from url.parse()
  • baseUrl - fully qualified uri string used as the base url. Most useful with request.defaults, for example when you want to do many requests to the same domain. If baseUrl is https://example.com/api/, then requesting /end/point?test=true will fetch https://example.com/api/end/point?test=true. When baseUrl is given, uri must also be a string.
  • method - http method (default: "GET")
  • headers - http headers (default: {})

  • qs - object containing querystring values to be appended to the uri
  • qsParseOptions - object containing options to pass to the qs.parse method. Alternatively pass options to the querystring.parse method using this format {sep:';', eq:':', options:{}}
  • qsStringifyOptions - object containing options to pass to the qs.stringify method. Alternatively pass options to the querystring.stringify method using this format {sep:';', eq:':', options:{}}. For example, to change the way arrays are converted to query strings using the qs module pass the arrayFormat option with one of indices|brackets|repeat
  • useQuerystring - if true, use querystring to stringify and parse querystrings, otherwise use qs (default: false). Set this option to true if you need arrays to be serialized as foo=bar&foo=baz instead of the default foo[0]=bar&foo[1]=baz.

  • body - entity body for PATCH, POST and PUT requests. Must be a Buffer, String or ReadStream. If json is true, then body must be a JSON-serializable object.
  • form - when passed an object or a querystring, this sets body to a querystring representation of value, and adds Content-type: application/x-www-form-urlencoded header. When passed no options, a FormData instance is returned (and is piped to request). See "Forms" section above.
  • formData - data to pass for a multipart/form-data request. See Forms section above.
  • multipart - array of objects which contain their own headers and body attributes. Sends a multipart/related request. See Forms section above.
    • Alternatively you can pass in an object {chunked: false, data: []} where chunked is used to specify whether the request is sent in chunked transfer encoding In non-chunked requests, data items with body streams are not allowed.
  • preambleCRLF - append a newline/CRLF before the boundary of your multipart/form-data request.
  • postambleCRLF - append a newline/CRLF at the end of the boundary of your multipart/form-data request.
  • json - sets body to JSON representation of value and adds Content-type: application/json header. Additionally, parses the response body as JSON.
  • jsonReviver - a reviver function that will be passed to JSON.parse() when parsing a JSON response body.
  • jsonReplacer - a replacer function that will be passed to JSON.stringify() when stringifying a JSON request body.

  • auth - a hash containing values user || username, pass || password, and sendImmediately (optional). See documentation above.
  • oauth - options for OAuth HMAC-SHA1 signing. See documentation above.
  • hawk - options for Hawk signing. The credentials key must contain the necessary signing info, see hawk docs for details.
  • aws - object containing AWS signing information. Should have the properties key, secret, and optionally session (note that this only works for services that require session as part of the canonical string). Also requires the property bucket, unless you’re specifying your bucket as part of the path, or the request doesn’t use a bucket (i.e. GET Services). If you want to use AWS sign version 4 use the parameter sign_version with value 4 otherwise the default is version 2. If you are using SigV4, you can also include a service property that specifies the service name. Note: you need to npm install aws4 first.
  • httpSignature - options for the HTTP Signature Scheme using Joyent's library. The keyId and key properties must be specified. See the docs for other options.

  • followRedirect - follow HTTP 3xx responses as redirects (default: true). This property can also be implemented as function which gets response object as a single argument and should return true if redirects should continue or false otherwise.
  • followAllRedirects - follow non-GET HTTP 3xx responses as redirects (default: false)
  • followOriginalHttpMethod - by default we redirect to HTTP method GET. you can enable this property to redirect to the original HTTP method (default: false)
  • maxRedirects - the maximum number of redirects to follow (default: 10)
  • removeRefererHeader - removes the referer header when a redirect happens (default: false). Note: if true, referer header set in the initial request is preserved during redirect chain.

  • encoding - encoding to be used on setEncoding of response data. If null, the body is returned as a Buffer. Anything else (including the default value of undefined) will be passed as the encoding parameter to toString() (meaning this is effectively utf8 by default). (Note: if you expect binary data, you should set encoding: null.)
  • gzip - if true, add an Accept-Encoding header to request compressed content encodings from the server (if not already present) and decode supported content encodings in the response. Note: Automatic decoding of the response content is performed on the body data returned through request (both through the request stream and passed to the callback function) but is not performed on the response stream (available from the response event) which is the unmodified http.IncomingMessage object which may contain compressed data. See example below.
  • jar - if true, remember cookies for future use (or define your custom cookie jar; see examples section)

  • agent - http(s).Agent instance to use
  • agentClass - alternatively specify your agent's class name
  • agentOptions - and pass its options. Note: for HTTPS see tls API doc for TLS/SSL options and the documentation above.
  • forever - set to true to use the forever-agent Note: Defaults to http(s).Agent({keepAlive:true}) in node 0.12+
  • pool - an object describing which agents to use for the request. If this option is omitted the request will use the global agent (as long as your options allow for it). Otherwise, request will search the pool for your custom agent. If no custom agent is found, a new agent will be created and added to the pool. Note: pool is used only when the agent option is not specified.
    • A maxSockets property can also be provided on the pool object to set the max number of sockets for all agents created (ex: pool: {maxSockets: Infinity}).
    • Note that if you are sending multiple requests in a loop and creating multiple new pool objects, maxSockets will not work as intended. To work around this, either use request.defaults with your pool options or create the pool object with the maxSockets property outside of the loop.
  • timeout - integer containing number of milliseconds, controls two timeouts.
    • Read timeout: Time to wait for a server to send response headers (and start the response body) before aborting the request.
    • Connection timeout: Sets the socket to timeout after timeout milliseconds of inactivity. Note that increasing the timeout beyond the OS-wide TCP connection timeout will not have any effect (the default in Linux can be anywhere from 20-120 seconds)

  • localAddress - local interface to bind for network connections.
  • proxy - an HTTP proxy to be used. Supports proxy Auth with Basic Auth, identical to support for the url parameter (by embedding the auth info in the uri)
  • strictSSL - if true, requires SSL certificates be valid. Note: to use your own certificate authority, you need to specify an agent that was created with that CA as an option.
  • tunnel - controls the behavior of HTTP CONNECT tunneling as follows:
    • undefined (default) - true if the destination is https, false otherwise
    • true - always tunnel to the destination by making a CONNECT request to the proxy
    • false - request the destination as a GET request.
  • proxyHeaderWhiteList - a whitelist of headers to send to a tunneling proxy.
  • proxyHeaderExclusiveList - a whitelist of headers to send exclusively to a tunneling proxy and not to destination.

  • time - if true, the request-response cycle (including all redirects) is timed at millisecond resolution. When set, the following properties are added to the response object:

    • elapsedTime Duration of the entire request/response in milliseconds (deprecated).
    • responseStartTime Timestamp when the response began (in Unix Epoch milliseconds) (deprecated).
    • timingStart Timestamp of the start of the request (in Unix Epoch milliseconds).
    • timings Contains event timestamps in millisecond resolution relative to timingStart. If there were redirects, the properties reflect the timings of the final request in the redirect chain:
      • socket Relative timestamp when the http module's socket event fires. This happens when the socket is assigned to the request.
      • lookup Relative timestamp when the net module's lookup event fires. This happens when the DNS has been resolved.
      • connect: Relative timestamp when the net module's connect event fires. This happens when the server acknowledges the TCP connection.
      • response: Relative timestamp when the http module's response event fires. This happens when the first bytes are received from the server.
      • end: Relative timestamp when the last bytes of the response are received.
    • timingPhases Contains the durations of each request phase. If there were redirects, the properties reflect the timings of the final request in the redirect chain:
      • wait: Duration of socket initialization (timings.socket)
      • dns: Duration of DNS lookup (timings.lookup - timings.socket)
      • tcp: Duration of TCP connection (timings.connect - timings.socket)
      • firstByte: Duration of HTTP server response (timings.response - timings.connect)
      • download: Duration of HTTP download (timings.end - timings.response)
      • total: Duration entire HTTP round-trip (timings.end)
  • har - a HAR 1.2 Request Object, will be processed from HAR format into options overwriting matching values (see the HAR 1.2 section for details)

  • callback - alternatively pass the request's callback in the options object

The callback argument gets 3 arguments:

  1. An error when applicable (usually from http.ClientRequest object)
  2. An http.IncomingMessage object (Response object)
  3. The third is the response body (String or Buffer, or JSON object if the json option is supplied)

back to top


Convenience methods

There are also shorthand methods for different HTTP METHODs and some other conveniences.

request.defaults(options)

This method returns a wrapper around the normal request API that defaults to whatever options you pass to it.

Note: request.defaults() does not modify the global request API; instead, it returns a wrapper that has your default settings applied to it.

Note: You can call .defaults() on the wrapper that is returned from request.defaults to add/override defaults that were previously defaulted.

For example:

//requests using baseRequest() will set the 'x-token' header
const baseRequest = request.defaults({
  headers: {'x-token': 'my-token'}
})

//requests using specialRequest() will include the 'x-token' header set in
//baseRequest and will also include the 'special' header
const specialRequest = baseRequest.defaults({
  headers: {special: 'special value'}
})

request.METHOD()

These HTTP method convenience functions act just like request() but with a default method already set for you:

  • request.get(): Defaults to method: "GET".
  • request.post(): Defaults to method: "POST".
  • request.put(): Defaults to method: "PUT".
  • request.patch(): Defaults to method: "PATCH".
  • request.del() / request.delete(): Defaults to method: "DELETE".
  • request.head(): Defaults to method: "HEAD".
  • request.options(): Defaults to method: "OPTIONS".

request.cookie()

Function that creates a new cookie.

request.cookie('key1=value1')

request.jar()

Function that creates a new cookie jar.

request.jar()

response.caseless.get('header-name')

Function that returns the specified response header field using a case-insensitive match

request('http://www.google.com', function (error, response, body) {
  // print the Content-Type header even if the server returned it as 'content-type' (lowercase)
  console.log('Content-Type is:', response.caseless.get('Content-Type')); 
});

back to top


Debugging

There are at least three ways to debug the operation of request:

  1. Launch the node process like NODE_DEBUG=request node script.js (lib,request,otherlib works too).

  2. Set require('request').debug = true at any time (this does the same thing as #1).

  3. Use the request-debug module to view request and response headers and bodies.

back to top


Timeouts

Most requests to external servers should have a timeout attached, in case the server is not responding in a timely manner. Without a timeout, your code may have a socket open/consume resources for minutes or more.

There are two main types of timeouts: connection timeouts and read timeouts. A connect timeout occurs if the timeout is hit while your client is attempting to establish a connection to a remote machine (corresponding to the connect() call on the socket). A read timeout occurs any time the server is too slow to send back a part of the response.

These two situations have widely different implications for what went wrong with the request, so it's useful to be able to distinguish them. You can detect timeout errors by checking err.code for an 'ETIMEDOUT' value. Further, you can detect whether the timeout was a connection timeout by checking if the err.connect property is set to true.

request.get('http://10.255.255.1', {timeout: 1500}, function(err) {
    console.log(err.code === 'ETIMEDOUT');
    // Set to `true` if the timeout was a connection timeout, `false` or
    // `undefined` otherwise.
    console.log(err.connect === true);
    process.exit(0);
});

Examples:

  const request = require('request')
    , rand = Math.floor(Math.random()*100000000).toString()
    ;
  request(
    { method: 'PUT'
    , uri: 'http://mikeal.iriscouch.com/testjs/' + rand
    , multipart:
      [ { 'content-type': 'application/json'
        ,  body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})
        }
      , { body: 'I am an attachment' }
      ]
    }
  , function (error, response, body) {
      if(response.statusCode == 201){
        console.log('document saved as: http://mikeal.iriscouch.com/testjs/'+ rand)
      } else {
        console.log('error: '+ response.statusCode)
        console.log(body)
      }
    }
  )

For backwards-compatibility, response compression is not supported by default. To accept gzip-compressed responses, set the gzip option to true. Note that the body data passed through request is automatically decompressed while the response object is unmodified and will contain compressed data if the server sent a compressed response.

  const request = require('request')
  request(
    { method: 'GET'
    , uri: 'http://www.google.com'
    , gzip: true
    }
  , function (error, response, body) {
      // body is the decompressed response body
      console.log('server encoded the data as: ' + (response.headers['content-encoding'] || 'identity'))
      console.log('the decoded data is: ' + body)
    }
  )
  .on('data', function(data) {
    // decompressed data as it is received
    console.log('decoded chunk: ' + data)
  })
  .on('response', function(response) {
    // unmodified http.IncomingMessage object
    response.on('data', function(data) {
      // compressed data as it is received
      console.log('received ' + data.length + ' bytes of compressed data')
    })
  })

Cookies are disabled by default (else, they would be used in subsequent requests). To enable cookies, set jar to true (either in defaults or options).

const request = request.defaults({jar: true})
request('http://www.google.com', function () {
  request('http://images.google.com')
})

To use a custom cookie jar (instead of request’s global cookie jar), set jar to an instance of request.jar() (either in defaults or options)

const j = request.jar()
const request = request.defaults({jar:j})
request('http://www.google.com', function () {
  request('http://images.google.com')
})

OR

const j = request.jar();
const cookie = request.cookie('key1=value1');
const url = 'http://www.google.com';
j.setCookie(cookie, url);
request({url: url, jar: j}, function () {
  request('http://images.google.com')
})

To use a custom cookie store (such as a FileCookieStore which supports saving to and restoring from JSON files), pass it as a parameter to request.jar():

const FileCookieStore = require('tough-cookie-filestore');
// NOTE - currently the 'cookies.json' file must already exist!
const j = request.jar(new FileCookieStore('cookies.json'));
request = request.defaults({ jar : j })
request('http://www.google.com', function() {
  request('http://images.google.com')
})

The cookie store must be a tough-cookie store and it must support synchronous operations; see the CookieStore API docs for details.

To inspect your cookie jar after a request:

const j = request.jar()
request({url: 'http://www.google.com', jar: j}, function () {
  const cookie_string = j.getCookieString(url); // "key1=value1; key2=value2; ..."
  const cookies = j.getCookies(url);
  // [{key: 'key1', value: 'value1', domain: "www.google.com", ...}, ...]
})

back to top

request-promise's People

Contributors

analog-nico avatar courajs avatar cwinters avatar erf avatar evancarroll avatar floatdrop avatar graingert avatar hildjj avatar jmm avatar jtwb2 avatar kukat avatar lexjacobs avatar luanmuniz avatar nodiis avatar not-an-aardvark avatar raineorshine avatar ratson avatar rebootjeff avatar rouanw avatar servel333 avatar shisama avatar syrok avatar tyabonil avatar yamsellem avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

request-promise's Issues

Weird issue when using Promise.settle w/ array of request-promises using `.finally()`

I have an array of request-promises that I am sending to Promise.settle, in each of these promises I am using the .finally() method and doing a return Promise.resolve(some_val); yet when I inspect my resolved value in the settle resolution, the Bluebird value() method returns undefined.

This seems to resolve itself if I move returning a new Promise inside my catch or then on the original request-promise.

doesn't work:

...
var req = rq('http://failing_domain_doesnt_resolve.com')
    .then(function(){})
    .catch(function(err){ // this gets called ok })
    .finally(function() {
         return Promise.resolve('I am ok!');
    });

Promise.settle([req])
    .then(function(results) {
        console.info(results[0].value()); // undefined
     });

Thanks for your work on this!

Error when using request methods

Calling rp.post() results in:

ReferenceError: key is not defined

See rp.js, Line 122:

function getParams(){
    var args = Array.prototype.slice.call(arguments, 0);
    var params = request.initParams.apply(request, args);
    params.method = methodNameLookup[key];
    return params;
}

error with nw.js

$ nw .
Possibly unhandled Error: TypeError: Illegal invocation
    at Object.ensureErrorObject (/Users/username/projects/rank/node_modules/request-promise/node_modules/bluebird/js/main/util.js:228:20)
    at Promise._rejectCallback (/Users/username/projects/rank/node_modules/request-promise/node_modules/bluebird/js/main/promise.js:416:22)
    at Promise._settlePromiseFromHandler (/Users/username/projects/rank/node_modules/request-promise/node_modules/bluebird/js/main/promise.js:460:17)
    at Promise._settlePromiseAt (/Users/username/projects/rank/node_modules/request-promise/node_modules/bluebird/js/main/promise.js:530:18)
    at Promise._settlePromises (/Users/username/projects/rank/node_modules/request-promise/node_modules/bluebird/js/main/promise.js:646:14)
    at Async._drainQueue (/Users/username/projects/rank/node_modules/request-promise/node_modules/bluebird/js/main/async.js:164:16)
    at Async._drainQueues (/Users/username/projects/rank/node_modules/request-promise/node_modules/bluebird/js/main/async.js:174:10)
    at Immediate.Async.drainQueues [as _onImmediate] (/Users/username/projects/rank/node_modules/request-promise/node_modules/bluebird/js/main/async.js:15:14)
    at processImmediate [as _immediateCallback] (timers.js:321:17)

Here's my code:

var rp = require('request-promise');

rp('http://www.google.com')
    .then(console.dir)
    .catch(console.error);

qs doesn't work

in the options object using

qs: { some: 'query' }

should append a ?some=query to the end of the request

Is there retry logic for bad connections?

Just wondering if the library itself has a utility flag/method or someone has a gist for retrying requests automatically?

For example, usecases like:

  1. 429 based rate limiting might require pause and retry
  2. connection timeout might require a retry

error when importing request-promise

I have installed request-promise via npm

npm i --save request-promise

Then I import it into a file:

import rq from 'request-promise'

Now I get this message:

ERROR in ./~/request-promise/~/request/lib/har.js
Module not found: Error: Cannot resolve module 'fs' in C:\Users\alex\ae\node_modules\request-promise\node_modules\reques
t\lib
 @ ./~/request-promise/~/request/lib/har.js 3:9-22

ERROR in ./~/request-promise/~/request/~/forever-agent/index.js
Module not found: Error: Cannot resolve module 'net' in C:\Users\alex\ae\node_modules\request-promise\node_modules\reque
st\node_modules\forever-agent
 @ ./~/request-promise/~/request/~/forever-agent/index.js 6:10-24

ERROR in ./~/request-promise/~/request/~/forever-agent/index.js
Module not found: Error: Cannot resolve module 'tls' in C:\Users\alex\ae\node_modules\request-promise\node_modules\reque
st\node_modules\forever-agent
 @ ./~/request-promise/~/request/~/forever-agent/index.js 7:10-24

ERROR in ./~/request-promise/~/request/~/tough-cookie/lib/cookie.js
Module not found: Error: Cannot resolve module 'net' in C:\Users\alex\ae\node_modules\request-promise\node_modules\reque
st\node_modules\tough-cookie\lib
 @ ./~/request-promise/~/request/~/tough-cookie/lib/cookie.js 32:10-24

ERROR in ./~/request-promise/~/request/~/tunnel-agent/index.js
Module not found: Error: Cannot resolve module 'net' in C:\Users\alex\ae\node_modules\request-promise\node_modules\reque
st\node_modules\tunnel-agent
 @ ./~/request-promise/~/request/~/tunnel-agent/index.js 3:10-24

ERROR in ./~/request-promise/~/request/~/tunnel-agent/index.js
Module not found: Error: Cannot resolve module 'tls' in C:\Users\alex\ae\node_modules\request-promise\node_modules\reque
st\node_modules\tunnel-agent
 @ ./~/request-promise/~/request/~/tunnel-agent/index.js 4:10-24

ERROR in ./~/request-promise/~/request/~/har-validator/~/is-my-json-valid/~/jsonpointer/jsonpointer.js
Module not found: Error: Cannot resolve module 'console' in C:\Users\alex\ae\node_modules\request-promise\node_modules\r
equest\node_modules\har-validator\node_modules\is-my-json-valid\node_modules\jsonpointer
 @ ./~/request-promise/~/request/~/har-validator/~/is-my-json-valid/~/jsonpointer/jsonpointer.js 1:14-32

This is my package.json, just in case:

{
  "name": "ae",
  "version": "1.0.0",
  "description": "arteigenschaften.ch",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server",
    "prebuild": "gulp cleanPublic",
    "build": "set NODE_ENV=production&& webpack",
    "test": "standard"
  },
  "author": "Alexander Gabriel",
  "license": "ISC",
  "dependencies": {
    "ampersand-app": "1.0.4",
    "ampersand-router": "3.0.2",
    "autolinker": "0.18.1",
    "autoprefixer-core": "5.2.1",
    "babel": "5.6.23",
    "babel-loader": "5.3.2",
    "bootstrap": "3.3.5",
    "classnames": "2.1.3",
    "css-loader": "0.15.5",
    "del": "1.2.0",
    "file-loader": "0.8.4",
    "gulp": "3.9.0",
    "hjs-webpack": "2.10.0",
    "jquery": "2.1.4",
    "json-loader": "0.5.2",
    "local-links": "1.4.0",
    "lodash": "3.10.0",
    "node-libs-browser": "0.5.2",
    "postcss-loader": "0.5.1",
    "pouchdb": "3.6.0",
    "pouchdb-all-dbs": "^1.0.1",
    "pouchdb-load": "^1.4.0",
    "react": "0.13.3",
    "react-bootstrap": "0.23.7",
    "react-favicon": "0.0.3",
    "react-hot-loader": "1.2.8",
    "react-json-inspector": "5.1.0",
    "react-textarea-autosize": "2.4.0",
    "react-typeahead": "^1.1.1",
    "reflux": "0.2.10",
    "request-promise": "^0.4.2",
    "require-dir": "0.3.0",
    "style-loader": "0.12.3",
    "stylus-loader": "1.2.1",
    "surge": "0.14.3",
    "url-loader": "0.5.6",
    "webpack": "1.10.1",
    "webpack-dev-server": "1.10.1",
    "yeticss": "7.0.1"
  },
  "standard": {
    "ignore": [
      "public/*"
    ]
  }
}

HEAD call useless without resolveWithFullResponse

As a HEAD call is a GET call without response body, it's pretty useless without the resolveWithFullResponse option, as you get an empty string all the time.

I personally would vote for having res.headers as the default parameter passed to .head() calls, or to at least set resolveWithFullResponse to true by default.

Or is it intended to preserve the same behavior in all convenience functions, even if it's nonsense to a particular function?

[Question] Get result for new request

I need results from request promise then() after, and use again result for new request ?? How do that?
I hope, have someone support my question. Thanks !

   let opt = {
        method: 'POST',
        uri: API,
        body: {
            news_id: id
        },
        json: true
    };

    rp(opt).then(function (result) {
        rpt(opt2).then(function () { // error
        })
    })

Reject with an error object

I ran into a problem when using this with mocha. The problem is because when rejecting, this library returns a JS object instead of an Error object. I'd like to open up discussion for changing it to return an error object instead. The options can still be put on there for introspection purposes, but I think it makes more sense to reject with a true Error.

From what I can tell, this is where it happens: https://github.com/tyabonil/request-promise/blob/master/lib/rp.js#L48-L58 and you have tests ensuring this is the case here

Issue also reported to mocha: mochajs/mocha#1532

Use Case: Wrap `pipe` events in promises

Thank you for putting this awesome abstraction together!

I came across a use case recently where I wanted to .pipe an arbitrary number of request results to my file system and .then finish my grunt task.

I would have loved to accomplish this via an abstraction of your library, I was wondering if you would consider looking at this use case and adding it out-of-the-box to your lib by wrapping pipe events in promises?

I accomplished it like so:

    var done = this.async();
    ...
          var downloaded = []; // make sure all the download pipes finish - step # 1
          var _ = require('underscore');
          var fs = require('fs');
          // GET for each resource
          _.each(paths, function(path){
            var filename = './downloded' + path + '.json';
            console.log(filename);
            var r = request
              .get(path)
              .on('error', function(err) {
                console.log(err);
                done();
              })
              // save in a file
              .pipe(fs.createWriteStream(filename));

            // make sure all the download pipes finish  - step # 2
            downloaded.push(
              new Promise(function (resolve, reject) {
                r.on('finish', function () {
                  console.log('pipe finished');
                  return resolve();
                });
              })
            );
          });

          // make sure all the download pipes finish - step # 3
          Promise.all(downloaded).then(function() {
            console.log('all the files were downloaded');
            done();
          });

Using request promise

Just to want to know best way to use rp below is a partial sample request structure that we have now.

Im trying out rp, do you have suggestion how this can be modified to make it better

request(option1, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        var data= JSON.parse(body);

        if(data.valid){

            if(data.expired){

                next();
            }else{

                request(option2, function (error2, response2, body2) {
                    var data2= JSON.parse(body2);
                    if(data2.valid) {
                        request(option3, function (error3, response3, body3) {
                            next();
                        })
                    } else {
                        res.json({success:false});
                    }
                })

            }
        }else{
            res.json({success:false});
        }
    }else{
        res.json({success:false});
    }
})

404 triggers then() instead of error()

During testing I've found that 404 responses are still resolved instead of rejected if no parameters except uri are set. As response only receives the body this can't even be noticed.
Imho- except from fixing this- it might make more sense to reply with the same parameters as the request module itself to make this lib more of a drop-in replacement.

timeout

Is there a way to set the timeout for the request?

How to handle an error in the body

Hey guys

I have this peculiar requirement to check the body for an error object, since the API that I'm working with will return a status code of 200 along with an error object in the body.

200 OK
{
  "error": "shitty API's error response"
}

Is there an easy way to define what should trigger an error, preferably using the defaults setting so that I can keep the codebase clean and DRY.

I've read up on the simple options, however I'm not sure of it's the right way to go.

In addition, I was hoping to use the transform function to reject the promise however the promise itself is not accessible from within the function?

Unless it's accessible in the transform using something like

this.promise().reject();

Thanks

Possible to stub with sinon.js?

Hello,

I'm trying to stub request-promise using sinon, however could not find a way yet on how to do that.
Back when i was using request itself, it looked something like this:

before(function (done) {
        sinon.stub(request, 'get').yields(null, { statusCode: 200 }, fs.readFileSync(__dirname + '/data/' + filename));
        done();
    });

    after(function (done) {
        request.get.restore();
        done();
    });
}

Any suggestions on how to do this with promise-request?
Feel free to close this issue if it doesn't fit in here.

What's considered "large quantities of data"

In the docs you write "If you stream large quantities of data the buffer grows big and that has an impact on your memory footprint. In these cases you can just var request = require('request'); and use request for streaming large quantities of data."

Have you done any test on this and is it possible to state in the docs where the typical limit is? Or is it too dependent on environment so that it's up to everyone to test ourselves?

Invalid URI should cause the promise to be rejected

var rq = require('request-promise');

rq('test').then(function(){
  console.log('success');
})
.catch(function(err){
  console.log('failed')
});

Expects the code to log 'failed' on console but instead throws error

Make a POST request with data on request body

I looked into the documentation and didnt find anything about it.

I'm wondering if I can make a POST passing the parameters into the body instead as a query string.

Is that possible?

POST request that results in 302 triggers catch

var request = require('request-promise');

request({
    url: 'http://httpstat.us/302',
    method: 'POST'
})
    .catch(function (error) {
        console.log(error);
    })
    .then(function () {
        console.log('OK')
    });

The error is just the incomingMessage object:

{ error: '302 Found',
  options:
   { method: 'POST',
     url: 'http://httpstat.us/302',
     callback: undefined,
     uri: undefined,
     tunnel: false,
     simple: true,
     resolveWithFullResponse: false },
  response:
   { _readableState:
      { objectMode: false,
        highWaterMark: 16384,
        buffer: [],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: true,
        ended: true,
        endEmitted: true,
        reading: false,
        sync: true,
        needReadable: false,
        emittedReadable: false,
        readableListening: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null,
        resumeScheduled: false },
     readable: false,
     domain: null,
     _events:
      { end: [Object],
        close: [Object],
        data: [Function],
        error: [Function] },
     _maxListeners: undefined,
     socket:
      { _connecting: false,
        _hadError: false,
        _handle: null,
        _host: 'httpstat.us',
        _readableState: [Object],
        readable: false,
        domain: null,
        _events: [Object],
        _maxListeners: 0,
        _writableState: [Object],
        writable: false,
        allowHalfOpen: false,
        destroyed: true,
        bytesRead: 422,
        _bytesDispatched: 79,
        _pendingData: null,
        _pendingEncoding: '',
        parser: null,
        _httpMessage: [Object],
        read: [Function],
        _consuming: true,
        _idleNext: null,
        _idlePrev: null,
        _idleTimeout: -1 },
     connection:
      { _connecting: false,
        _hadError: false,
        _handle: null,
        _host: 'httpstat.us',
        _readableState: [Object],
        readable: false,
        domain: null,
        _events: [Object],
        _maxListeners: 0,
        _writableState: [Object],
        writable: false,
        allowHalfOpen: false,
        destroyed: true,
        bytesRead: 422,
        _bytesDispatched: 79,
        _pendingData: null,
        _pendingEncoding: '',
        parser: null,
        _httpMessage: [Object],
        read: [Function],
        _consuming: true,
        _idleNext: null,
        _idlePrev: null,
        _idleTimeout: -1 },
     httpVersionMajor: 1,
     httpVersionMinor: 1,
     httpVersion: '1.1',
     complete: true,
     headers:
      { 'cache-control': 'private',
        'content-length': '9',
        'content-type': 'text/plain; charset=utf-8',
        location: 'http://httpstat.us',
        server: 'Microsoft-IIS/8.0',
        'x-aspnetmvc-version': '5.1',
        'x-aspnet-version': '4.0.30319',
        'x-powered-by': 'ASP.NET',
        'set-cookie': [Object],
        date: 'Thu, 08 Jan 2015 15:52:34 GMT',
        connection: 'close' },
     rawHeaders:
      [ 'Cache-Control',
        'private',
        'Content-Length',
        '9',
        'Content-Type',
        'text/plain; charset=utf-8',
        'Location',
        'http://httpstat.us',
        'Server',
        'Microsoft-IIS/8.0',
        'X-AspNetMvc-Version',
        '5.1',
        'X-AspNet-Version',
        '4.0.30319',
        'X-Powered-By',
        'ASP.NET',
        'Set-Cookie',
        'ARRAffinity=0289d9a2e779a2431db31b4a154e84828a77f89dbbe1fe391d5fe9794f54f970;Path=/;Domain=httpstat.us',
        'Date',
        'Thu, 08 Jan 2015 15:52:34 GMT',
        'Connection',
        'close' ],
     trailers: {},
     rawTrailers: [],
     _pendings: [],
     _pendingIndex: 0,
     upgrade: false,
     url: '',
     method: null,
     statusCode: 302,
     statusMessage: 'Found',
     client:
      { _connecting: false,
        _hadError: false,
        _handle: null,
        _host: 'httpstat.us',
        _readableState: [Object],
        readable: false,
        domain: null,
        _events: [Object],
        _maxListeners: 0,
        _writableState: [Object],
        writable: false,
        allowHalfOpen: false,
        destroyed: true,
        bytesRead: 422,
        _bytesDispatched: 79,
        _pendingData: null,
        _pendingEncoding: '',
        parser: null,
        _httpMessage: [Object],
        read: [Function],
        _consuming: true,
        _idleNext: null,
        _idlePrev: null,
        _idleTimeout: -1 },
     _consuming: true,
     _dumped: false,
     req:
      { domain: null,
        _events: [Object],
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        writable: true,
        _last: true,
        chunkedEncoding: false,
        shouldKeepAlive: false,
        useChunkedEncodingByDefault: true,
        sendDate: false,
        _removedHeader: [Object],
        _hasBody: true,
        _trailer: '',
        finished: true,
        _hangupClose: false,
        socket: [Object],
        connection: [Object],
        agent: [Object],
        socketPath: undefined,
        method: 'POST',
        path: '/302',
        _headers: [Object],
        _headerNames: [Object],
        _header: 'POST /302 HTTP/1.1\r\nhost: httpstat.us\r\ncontent-length: 0\r\nConnection: close\r\n\r\n',
        _headerSent: true,
        parser: null,
        res: [Circular] },
     request:
      { domain: null,
        _events: [Object],
        _maxListeners: undefined,
        uri: [Object],
        callback: [Function],
        method: 'POST',
        readable: true,
        writable: true,
        explicitMethod: true,
        canTunnel: false,
        _rp_resolve: [Function],
        _rp_reject: [Function],
        _rp_promise: [Object],
        _rp_callbackOrig: undefined,
        _rp_options: [Object],
        headers: [Object],
        setHeader: [Function],
        hasHeader: [Function],
        getHeader: [Function],
        removeHeader: [Function],
        localAddress: undefined,
        qsLib: [Object],
        pool: {},
        dests: [],
        __isRequestRequest: true,
        _callback: [Function: RP$callback],
        proxy: null,
        tunnel: false,
        _redirectsFollowed: 0,
        maxRedirects: 10,
        allowRedirect: [Function],
        followRedirects: true,
        followAllRedirects: false,
        redirects: [],
        setHost: true,
        originalCookieHeader: undefined,
        _disableCookies: true,
        _jar: undefined,
        port: 80,
        host: 'httpstat.us',
        path: '/302',
        httpModule: [Object],
        agentClass: [Object],
        agent: [Object],
        _rp_promise_in_use: true,
        _started: true,
        href: 'http://httpstat.us/302',
        req: [Object],
        ntick: true,
        response: [Circular],
        originalHost: 'httpstat.us',
        originalHostHeaderName: 'host',
        _destdata: true,
        _ended: true,
        _callbackCalled: true },
     toJSON: [Function: responseToJSON],
     caseless: { dict: [Object] },
     read: [Function],
     body: '302 Found' },
  statusCode: 302 }

poor error message

When an error occurs in a request, I get this printed out (directly after whatever error message I print for the error):

/usrdata/web/facebook-insights-cli/node_modules/request-promise/node_modules/bluebird/js/main/async.js:36
        fn = function () { throw arg; };
                                 ^
TypeError: undefined is not a function
  at module.exports (/usrdata/web/facebook-insights-cli/node_modules/request-promise/lib/rp.js:158:9)
  at Function.CapturedTrace.fireRejectionEvent (/usrdata/web/facebook-insights-cli/node_modules/request-promise/node_modules/bluebird/js/main/captured_trace.js:214:17)
  at Promise._notifyUnhandledRejection (/usrdata/web/facebook-insights-cli/node_modules/request-promise/node_modules/bluebird/js/main/promise.js:889:23)
  at Async._drainQueue (/usrdata/web/facebook-insights-cli/node_modules/request-promise/node_modules/bluebird/js/main/async.js:84:12)
  at Async._drainQueues (/usrdata/web/facebook-insights-cli/node_modules/request-promise/node_modules/bluebird/js/main/async.js:91:10)
  at Async.drainQueues (/usrdata/web/facebook-insights-cli/node_modules/request-promise/node_modules/bluebird/js/main/async.js:14:14)
  at process._tickCallback (node.js:419:13)

...which isn't very helpful.

Parameter uri not being set from parameter url

This is a 0.2.x specific bug.
I have installed the following components:

[email protected] node_modules/request-promise
├── [email protected]
└── [email protected]

If I try like this:

'use strict';

var rp = require('request-promise');
var options = {
    url: 'http://google.com.br',
};

rp.get(options)
.then(function(response){
    console.log(response);
}).catch(function(reason){
    console.log(reason);
});

I get the following reason logged:

Error: options.uri is a required argument

However, if I change url to uri, it works just as expected.

These two parameters should relfect each other.

Undefined header value yields an error that cannot be handled

I am using request-promise and I got a mysterious error:

Uncought exception Error: `value` required in setHeader("cookie", value).
at ClientRequest.OutgoingMessage.setHeader (_http_outgoing.js:339:11)
at new ClientRequest (_http_client.js:80:14)
at Object.exports.request (http.js:31:10)
at Request.start (/opt/myapp/webapp/lib/app/frontend/node_modules/request/request.js:904:30)
at Request.end (/opt/myapp/webapp/lib/app/frontend/node_modules/request/request.js:1635:10)
at end (/opt/myapp/webapp/lib/app/frontend/node_modules/request/request.js:676:14)
at Immediate._onImmediate (/opt/myapp/webapp/lib/app/frontend/node_modules/request/request.js:690:7)
at processImmediate [as _immediateCallback] (timers.js:374:17)

seems that if you do a:

rp({
  uri: 'http://localhost:60000/some/route',
  method: 'GET',
  resolveWithFullResponse: true,
  headers: {
    cookie: undefined
  }
});

you will get an exception that cannot be handled

export `RequestError` and `StatusCodeError`

Since I want to reliably detect what type of error occured, I need to check err in the error handler using err instanceof …. This is only possible if request-promise exports the constructors. Please do so.

How to handle cookies?

Hi!
Before of using this lib, I was using the non-promise version of request, where I was able to send into a GET also some cookies, as the follow:

var j = req.jar();
var url = "my_url";
var cookie = req.cookie("" + mycookie);
j.setCookie(cookie, url);
req({ uri: url, method: "GET", jar: j }, function(....));

By now with the same options, but using promise-request, I'm getting an error into catch function, saying just this:
[SyntaxError: Unexpected token u]

Am I missing something?
Thanks in advance!

Failing test

Currently the last test (resolveWithFullResponse should include the response) is failing.

The reason for the failure is that the options object still contains uri: 'http://localhost:4000/500' from a preceding test (simple tests should reject for 500 status code). Since the test sets url instead of uri both properties are set and request uses the uri in the end.

To solve this the options objects should be properly initialized for each call without producing such side effects.

Please let me know if I should do the fix.

How do you handle error responses properly?

So I'm using request-promise in a script that I have that loops through a list of urls and fires of requests. then I want to do something w/ the data received once all the requests are complete.

I have the following:

var rp = require('request-promise');

rp.get({
            uri: 'http://httpstat.us/500',
            transform: function(body, res){
                res.data = JSON.parse(body);
                return res;
            }
        }).then(function(res){
            results.push(res.data);
        })
        .catch(function(err){
            should.throw.error.to.console();
            var respErr  = JSON.parse(err.error);
            var errorResult = {
                origUrl: respErr.origUrl,
                error: respErr
            };
            results.push(errorResult);
        });

As you can see.. http://httpstat.us/500 throws a 500, which causes the .catch() block to be ran. I'm forcing an error. should.throw.error.to.console(); should throw an error to the console, but instead, the script just exits silently w/o any error code (Process finished with exit code 0).

I'm assuming that you're catching the error from node's http when a page doesn't come back w/ 2xx code and then passing that back to the catch() callback. But any subsequent errors then end up failing silently. How in the world do I handle this so that the rest of my code will still throw errors properly?

CLS and Promises

Is there a way to patch this so CLS works inside the Promises without having to fork and patch the entire thing with cls-bluebird?

Async transfrom via promise

Is it possible to let transform be able to resolve a promise? like this:

options.transform = function (data) {
  return new Promise(function(resolve) {
    setTimeout(function() { resolve(1); }, 1);
  });
};

rp(options)
    .then(function(res) {
      // `res` will be `1`
    });

Travis CI integration

Hi @tyabonil

I just added the .travis.yml so that Travis CI can build this project. This is especially helpful when we get a pull request because Travis CI then builds the sources as if the pull request was pulled in and reports the result to the pull request page.

All you need to do is to:

  1. sign in to Travis CI with your GitHub account,
  2. go to your profile page, and
  3. switch on the switch for this repository.

Thats it! Thanks!

post param

Dear,
Is it possible to add a post parameter ? I couldn't find a way to add them and couldn't find neither a test nor an example.

Error thrown on 3xx HTTP status

Possibly unhandled StatusCodeError: 302 - 
    at new StatusCodeError (/[...]/node_modules/request-promise/lib/errors.js:26:15)
    at Request.RP$callback [as _callback] (/[...]/node_modules/request-promise/lib/rp.js:64:32)
    at Request.self.callback (/[...]/node_modules/request/request.js:198:22)
    at emitTwo (events.js:87:13)
    at Request.emit (events.js:172:7)
    at Request.<anonymous> (/[...]/node_modules/request/request.js:1063:14)
    at emitOne (events.js:82:20)
    at Request.emit (events.js:169:7)
    at IncomingMessage.<anonymous> (/[...]/node_modules/request/request.js:1009:12)
    at emitNone (events.js:72:20)
    at IncomingMessage.emit (events.js:166:7)
    at endReadableNT (_stream_readable.js:893:12)
    at doNTCallback2 (node.js:429:9)
    at process._tickCallback (node.js:343:17)

This makes followRedirect set to false unusable.

No standard error object?

Why aren't you returning a standard error object?

rp("http://google.com/foobar")
    .then(console.dir)
    .catch( function(err) {
        //err should be a standard error object but is just "404"
        console.error("logging error", err);
        throw err;
    });

Possibly unhandled StatusCodeError: 400

When i receive the StatusCode 400 from a server i have this error

Possibly unhandled StatusCodeError: 400 - { errorMessage: "Unable to complete Request", errorCode: 1 }
    at new StatusCodeError (/api/node_modules/request-promise/lib/errors.js:26:15)
    at Request.RP$callback [as _callback] (/api/node_modules/request-promise/lib/rp.js:58:34)
    at Request.self.callback (/api/node_modules/request/request.js:360:22)
    at Request.emit (events.js:110:17)
    at Request.<anonymous> (/api/node_modules/request/request.js:1202:14)
    at Request.emit (events.js:129:20)
    at IncomingMessage.<anonymous> (/api/node_modules/request/request.js:1150:12)
    at IncomingMessage.emit (events.js:129:20)
    at _stream_readable.js:908:16
    at process._tickCallback (node.js:355:11)

Should i post this issue at the request module?

timeout option not working

So I set up the following:

var rp = require('request-promise');

var start = Date.now();
var reqPromise = rp({
    method: 'get',
    uri: 'http://localhost:8080/test-connection-length',
    timeout: 600000, // 10 min.
    resolveWithFullResponse: true
});

var interval = setInterval(function(){
    console.log('Waiting: ', (Date.now() - start) / 1000);
}, 1000);

reqPromise.then(function(resp){
    console.log('got response: ', resp);
})
.catch(function(err){
    console.error(err.toString());
    console.error(err.stack);
})
.finally(function(){
        console.log('Done: ', (Date.now() - start) / 1000);
    clearInterval(interval);
});

The test server endpoint just sits and doesn't respond, writing a similar console log every second as well.

Even though I have a 10min timeout set, the result is the following in the client:

Waiting:  116.464
Waiting:  117.469
Waiting:  118.475
RequestError: Error: socket hang up
RequestError: Error: socket hang up
Waiting:  119.481
    at new RequestError (/Users/matthewmarcus/WebStormProjects/CaptoraInc/capture-site-validation/node_modules/request-promise/lib/errors.js:11:15)
Done:  120.03
    at Request.RP$callback [as _callback] (/Users/matthewmarcus/WebStormProjects/CaptoraInc/capture-site-validation/node_modules/request-promise/lib/rp.js:50:34)
    at self.callback (/Users/matthewmarcus/WebStormProjects/CaptoraInc/capture-site-validation/node_modules/request-promise/node_modules/request/request.js:197:22)
    at Request.emit (events.js:107:17)
    at Request.onRequestError (/Users/matthewmarcus/WebStormProjects/CaptoraInc/capture-site-validation/node_modules/request-promise/node_modules/request/request.js:854:8)
    at ClientRequest.emit (events.js:107:17)
    at Socket.socketOnEnd (_http_client.js:300:9)
    at Socket.emit (events.js:129:20)
    at _stream_readable.js:908:16
    at process._tickCallback (node.js:355:11)

Process finished with exit code 0

Shouldn't this happen at 10mins, not 2?

Lodash error using request promise

While making a get request, I get the following error

"Uncaught TypeError: _.assign is not a function", source: /Users/ZECTbynmo/Projects/ConnectorTester/node_modules/request-promise/lib/rp.js (19)

Any ideas?

New Updated Code Breaks Promise Functions

This was meant to be a combination of both request and bluebird.

But now with the API changes you will no longer be able to use any of bluebird's methods other than .then and .catch.Especially one as useful as .bind(this).

Question: Will you be somehow proxying methods to Bluebird in an upcoming release or is this the way you will go from now on just adding prototyp methods directly to the request object?

Can this be used in client side ?

Is there any way for this package to be used in client side ?
I'm looking for a non-jquery node module to be used in client-side, and pack it via webpack.
This module seemed to be good but the requirement of fs doesn't let webpack to work with it.

Is there any workaround for this ? or any way to just load enough scripts for client side to pack ?

Aligning on a jshintrc

Hi Ty, I just committed the gulp integration. I loosened the settings in the .jshintrc so no changes to the sources were needed. The following rules could be activated again (but would need small changes in the code):

  1. curly (Require {} for every new block or scope.)
  2. latedef (Prohibit variable use before definition.)
  3. strict (Require use strict pragma in every file.)
  4. asi (Do not tolerate Automatic Semicolon Insertion (no semicolons).)
  5. sub (Do not tolerate all forms of subscript notation besides dot notation e.g. dict['key'] instead of dict.key.)
  6. Remove Promise global (See: jshint/jshint#1747)

I usually have all but number 5 activated. How would you like to configure it?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.