Coder Social home page Coder Social logo

request-promise-native'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-native's People

Contributors

analog-nico avatar jasonmit avatar shisama avatar sophieklm avatar thebigbignooby 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

request-promise-native's Issues

request.cancel() is not a function

I have the following code:

const rq = require("request-promise-native");
rq('https://www.google.co.uk').cancel();

but i get:

TypeError: rq(...).cancel is not a function

global.XMLHttpRequest is not a constructor

I'm building a small library.

  • Using following versions:
 "request": "^2.83.0",
 "request-promise-native": "^1.0.5",
  • Injecting the package as follows:
import request from 'request-promise-native';

Building UMD package so it could be used all kinds of ways. Browser and Node. Using webpack as a bundle tool.

When I inject the output as script tag and use use instance of the library and call methods ( using request ) everything works fine.

When I used node repl to test when I require my output file I receive this.

TypeError: global.XMLHttpRequest is not a constructor

Time request setting not returning info about the timing of the call

In main request docs https://github.com/request/request there is an option called "time" that in case is set to true is supposed to add additional details about the time of the transaction:

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 ...

Adding the flag into my request options I do not get the information I need.

Here the code of my request:

const options = {
        url: '...',
        headers: '...',
        json: true,
        method:"GET",
        time: true,
        timeout: 5000
}

request(options)
        .then(response => {
              // --> Response object only returning the body of my request.
         }

"getaddrinfo ENOTFOUND" error

I recently came across this issue when using request-promise-native. When sending a GET or POST request to certain URLs, I received a "getaddrinfo ENOTFOUND" error. This seems to happen randomly (i.e. some URL requests would throw this error during one run but work completely fine on the next). After some Googling, I found this issue:

nodejs/node#5436 (comment)

Although I didn't find this documented in the request-promise page, I added {"family": 4} to the options, and I stopped getting the error. It might be useful to either set "family" to 4 by default or just make a note of this in the documentation.

Support .finally(...)

Promise.prototype.finally is introduced in ES2018, but the README indicates that it is "not available".

Add "Usage" to the README

Hi.

I think the README could benefit from a short "Usage" section below the "Installation" section.
It should show what you should actually require() in your code - require('request') OR require('request-promise-native').

Thanks.

Request promise never return to **then** or **catch** sections in type script.

Request promise never return to then or catch sections in type script.

Node 8.11.1

import * as  request from 'request-promise-native';

            const httpParams = {
                uri: this.config.restBaseURL,
                qs: endPoint,
                method: 'POST',
                body: data,
                json: true,
                headers: headers,
                oauth: oAuth
            };

request(httpParams).then(res => {
                return res;
            }).catch(err => {
                throw err;
            });

"request": "^2.81.0",
"request-promise-native": "^1.0.5",

Documentation does not help the request user

The request package suggests that:

If you'd like request to return a Promise instead, you can use an alternative interface wrapper for request.

It then proceeds to suggest request-promise-native for native Promises.

The problem is that the request-promise-native package's documentation is minimal, and will probably mislead most request users who are simply looking to promisify their code.

Specific examples include:

  • the documentation says that you need to npm install both request and request-promise-native, but then fails to indicate that your code should require('request-promise-native') rather than require('request'). This might seem minor, but it's likely to be very confusing to newcomers from request.
  • the API appears to be quite different, but there is no documentation to this effect. For example, to retrieve content-type from request.head is rc.headers.get('content-type') but with request-promise-native is rc['content-type']

As it stands, I suspect the casual request user would be better-served by simply using util.promisify. It would be good to write some basic documentation.

Unmet peer dependency even with request installed

I'm sorry to bring this up yet again but hear me out. I saw many other issues in this repo related but the answer was always "Install request first". I have done that but I'm still getting the error. I have even tried installing [email protected] specifically with the same result. The package that is installed is [email protected] however. I'm guessing this could have something to do with it. Otherwise I'm lost!

I am using the Ubuntu WSL on Windows 10 if that makes a difference. I can't test on a real Ubuntu install so maybe this is unique to WSL since I'm not seeing this issue from others?

Below are the commands I have run exactly and their output.

akeenan / ~ > npm install -g request
/home/akeenan/.node_modules/lib
└─┬ [email protected]
  ├── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├─┬ [email protected]
  │ └── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├─┬ [email protected]
  │ └── [email protected]
  ├─┬ [email protected]
  │ ├─┬ [email protected]
  │ │ ├── [email protected]
  │ │ ├── [email protected]
  │ │ ├── [email protected]
  │ │ └─┬ [email protected]
  │ │   └── [email protected]
  │ └── [email protected]
  ├─┬ [email protected]
  │ ├── [email protected]
  │ ├─┬ [email protected]
  │ │ ├── [email protected]
  │ │ ├── [email protected]
  │ │ └─┬ [email protected]
  │ │   └── [email protected]
  │ └─┬ [email protected]
  │   ├── [email protected]
  │   ├── [email protected]
  │   ├── [email protected]
  │   ├── [email protected]
  │   ├── [email protected]
  │   ├── [email protected]
  │   ├── [email protected]
  │   └── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├─┬ [email protected]
  │ └── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├─┬ [email protected]
  │ ├── [email protected]
  │ └── [email protected]
  ├── [email protected]
  └── [email protected]

akeenan / ~ > npm install -g request-promise-native
/home/akeenan/.node_modules/lib
├── UNMET PEER DEPENDENCY request@^2.34
└─┬ [email protected]
  ├── UNMET PEER DEPENDENCY request@^2.34
  ├─┬ [email protected]
  │ └── [email protected]
  ├── [email protected]
  └─┬ [email protected]
    ├── [email protected]
    └── [email protected]

npm WARN [email protected] requires a peer of request@^2.34 but none was installed.
npm WARN [email protected] requires a peer of request@^2.34 but none was installed.
akeenan / ~ >

Embed request as dependency

Hi there,

why is request not installed as dependency in request-promise-native? I think it is overhead to install it manually when only using request-promise-native - people who use dependency checkers will have failing pipelines, because it is unused. Or is there another reason?

Best
Philipp

(node:2180) MaxListenersExceededWarning: Possible EventEmitter memory leak detected

Getting (node:2180) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 pipe listeners added. Use emitter.setMaxListeners() to increase limit in node v8 and v10 and rp1.0.5

(node:2180) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 pipe listeners added. Use emitter.setMaxListeners() to increase limit
    at _addListener (events.js:243:17)
    at Request.addListener (events.js:259:10)
    at Request.init (/e3v/node_modules/request/request.js:493:8)
    at Request.RP$initInterceptor [as init] (/e3v/node_modules/request-promise-core/configure/request2.js:45:29)
    at Redirect.onResponse (/e3v/node_modules/request/lib/redirect.js:149:11)
    at Request.onRequestResponse (/e3v/node_modules/request/request.js:993:22)
    at ClientRequest.emit (events.js:182:13)
    at ClientRequest.EventEmitter.emit (domain.js:442:20)
    at HTTPParser.parserOnIncomingClient (_http_client.js:538:21)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:109:17)

Lose stack trace?

StatusCodeError: 500 - "Internal error"
    at new StatusCodeError (/app/node_modules/request-promise-core/lib/errors.js:32:15)
    at Request.plumbing.callback (/app/node_modules/request-promise-core/lib/plumbing.js:104:33)
    at Request.RP$callback [as _callback] (/app/node_modules/request-promise-core/lib/plumbing.js:46:31)
    at Request.self.callback (/app/node_modules/request/request.js:185:22)
    at Request.emit (events.js:182:13)
    at Request.EventEmitter.emit (domain.js:441:20)
    at Request.<anonymous> (/app/node_modules/request/request.js:1161:10)
    at Request.emit (events.js:182:13)
    at Request.EventEmitter.emit (domain.js:441:20)
    at IncomingMessage.<anonymous> (/app/node_modules/request/request.js:1083:12)
    at Object.onceWrapper (events.js:273:13)
    at IncomingMessage.emit (events.js:187:15)
    at IncomingMessage.EventEmitter.emit (domain.js:441:20)
    at endReadableNT (_stream_readable.js:1094:12)
    at process._tickCallback (internal/process/next_tick.js:63:19)

I get this as a stack trace.

Notice how, it doesn't tell me the original function that called rp.get(options) for example.

aka I can't tell which of my many API requests is failing.

I know this is probably a known issue/mentioned somewhere else. What's the workaround/fix for this? Does the problem go all the way back to request-promise-core or even request itself?

I'm using "request-promise-native": "^1.0.5", but I'm willing to bet it's happening in any/all versions?

Update README regarding Targetted Catch blocks.

The README says:

Everything applies to request-promise-native except the following:

  • Instead of using Bluebird promises this library uses native ES6 promises.
  • Mind that native ES6 promises have fewer features than Bluebird promises do. In particular, the .finally(...) method is not available.

And for somebody unfamiliar with Bluebird promises, it is not immediately obvious that native Promises do not support targeted catch blocks. Somebody (like me) might just think it's a little-known feature of Promises and end up banging their head on things until they eventually find this:
#15 (comment)

'Cannot find lodash/isFunction'

Hi,

On build my app throws the error cannot find module lodash/isFunction, tracing back to request-promise-native. I've tried deleting my node modules folder and reinstalling everything. Does this sound like an inherent error or should I attempt a different fix?

Thanks.

Catch with errors.StatusCodeError doesn't work if a generic exception is thrown

When using native promises .catch() with error filter, if the function with received body throws an error, the constructor of the error itself throws another error.

TypeError: Cannot set property 'name' of undefined
at StatusCodeError (/home/user/project/node_modules/request-promise-core/lib/errors.js:24:15)

Using this require syntax

const request = require('request-promise-native');
const errors = require('request-promise-native/errors');

consider the following snippet, when the REST API returns status='error':

return request(options)
      .then((reply) => {
        if (reply.status === 'ok') {
          return (reply.data.user.email === user.email);
        } else {
          throw new Error(reply.message || 'Authentication service error');
        }
      }).catch(errors.StatusCodeError, err => {
        if (err.statusCode === 401) {
          console.error('AuthService rejected our authentication settings');
        } else throw err;
      });

NodeJS: 12.8.0
npm: 6.10.2

UnhandledPromiseRejectionWarning when using with Request

Using the original request library to make HTTP calls and handle errors. Generally works fine.

However if I import request-promise-native, even if it's not used, it'll cause UnhandledPromiseRejectionWarning - seems to be interfering with my API calls made with request. Requiring request-promise (Bluebird) does not cause this issue - Node GC only catches native promises.

Using Node 8.10.0 LTS.

Can be reproduced with below

const request = require('request');
require('request-promise-native');

const main = async () => new Promise((resolve, reject) => {
    request.get({url: `http://google.com/non-existent`})
        .on('response', async response => {
            if (response.statusCode !== 200) {
                return reject({
                    statusCode: response.statusCode
                });
            }
            resolve();
        })
});


test('test 404', async () => {
    expect.assertions(1);
    try {
        await main();
    } catch (e) {
        expect(e.statusCode).toBe(404);
    }
});

package.json

{
  "dependencies": {
    "request": "^2.85.0",
    "request-promise-native": "^1.0.5"
  },
  "devDependencies": {
    "jest": "^22.4.3"
  }
}

Any access to response object?

The request library shows the callback as function (error, response, body), I figured the error parameter would only show up in the catch(err) handler but it appears only body is passed in for the then() handler.

having some issues with react native

Failed to load bundle(http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false) with error:(Unable to resolve module crypto from /Users/macpro/test/node_modules/request/lib/helpers.js: Module crypto does not exist in the Haste module map

This might be related to facebook/react-native#4968
To resolve try the following:

  1. Clear watchman watches: watchman watch-del-all.
  2. Delete the node_modules folder: rm -rf node_modules && npm install.
  3. Reset Metro Bundler cache: rm -rf /tmp/metro-bundler-cache-* or npm start -- --reset-cache.
  4. Remove haste cache: rm -rf /tmp/haste-map-react-native-packager-*. (null))

__38-[RCTCxxBridge loadSource:onProgress:]_block_invoke.213
RCTCxxBridge.mm:414
invocation function for block in attemptAsynchronousLoadOfBundleAtURL(NSURL*, void (RCTLoadingProgress*) block_pointer, void (NSError*, RCTSource*) block_pointer)
__80-[RCTMultipartDataTask URLSession:streamTask:didBecomeInputStream:outputStream:]_block_invoke
-[RCTMultipartStreamReader emitChunk:headers:callback:done:]
-[RCTMultipartStreamReader readAllPartsWithCompletionCallback:progressCallback:]
-[RCTMultipartDataTask URLSession:streamTask:didBecomeInputStream:outputStream:]
_CFNetworkHTTPConnectionCacheSetLimit
NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK
-[NSBlockOperation main]
NSOPERATION_IS_INVOKING_MAIN
-[NSOperation start]
NSOPERATIONQUEUE_IS_STARTING_AN_OPERATION
__NSOQSchedule_f
_dispatch_block_async_invoke2
_dispatch_client_callout
_dispatch_continuation_pop
_dispatch_async_redirect_invoke
_dispatch_root_queue_drain
_dispatch_worker_thread2
_pthread_wqthread
start_wqthread

async/await

Why doesn't async/await work like it does in other async libraries?

when I call:
let result = await request(options), it's returning a promise and not the resolved value. I thought the whole idea of await is so you can await for the async function embedded in the Promise to complete. But in the case of this library, it's just returning the promise.

UNMET PEER DEPENDENCY

getting this error below on a clean app with no other packages...

[~/dev/rikai/provisioning]$ npm install                                                                                      *[master] 
[email protected] /Users/dc/dev/rikai/provisioning
├── UNMET PEER DEPENDENCY request@^2.34
└─┬ [email protected] 
  ├── UNMET PEER DEPENDENCY request@^2.34
  ├─┬ [email protected] 
  │ └── [email protected] 
  └── [email protected] 

npm WARN [email protected] requires a peer of request@^2.34 but none was installed.
npm WARN [email protected] requires a peer of request@^2.34 but none was installed.
npm WARN [email protected] No description
[~/dev/rikai/provisioning]$ cat package.json                                                                                 *[master] 
{
  "name": "provisioning",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/dcsan/provisioning.git"
  },
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/dcsan/provisioning/issues"
  },
  "homepage": "https://github.com/dcsan/provisioning#readme",
  "dependencies": {
    "request-promise-native": "^1.0.3"
  }
}

DeprecationWarning when piping to createWriteStream

I'm using the recommended? way to stream a request to a file, and use await to wait until I can move to downloading the next file in my queue.

const r = request(file.url);
r.pipe(fs.createWriteStream(file.target));
await r;

Simple enough. And it absolutely completely works. But, occasionally I get a warning:

DeprecationWarning: Calling an asynchronous function without callback is deprecated

Does it need a callback then? And where, what should I put into it?

Also, I'm a noob on node (expert on general javascript though) so I might not be doing it correctly. If that's the case, please do show me a correct(er) way to "just" download a binary file and wait for it.

I'm on NodeJS 7.10 and Windows 10, if that helps.

Unhandled promise rejection.

When I do a request using the following:

      response = await requestPromise({
        uri: requestUrl,
        method: method,
        simple: false,
        resolveWithFullResponse: true,
        json: true,
        qs: queryString,
      });
    } catch (err) {
      throw new Error("Something is wrong");
    }```

It appears to work. but in the console log I see an error that says:

```(node:21521) UnhandledPromiseRejectionWarning: #<Object>
(node:21521) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:21521) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.```

I suspect something in the library is not awaiting on a Promise some where.

Transform Error ?

What does that mean ?

TransformError: RangeError: Maximum call stack size exceeded

Automatically stringifying the body to JSON in POST operations

Hi there!

I've been using this library for node microservices and found out something that I didn't quite understand the other day. Through looking at the docs of request-promise I realized that you can specify that the response of a POST operation to be automatically stringify

var options = {
    method: 'POST',
    uri: 'http://api.posttestserver.com/post',
    body: {
        some: 'payload'
    },
    json: true // Automatically stringifies the body to JSON
};

However, I don't think that is currently supported for request-promise-native. Is that right? Would it be good to have support for that?

Thank you! 😄

Request acts like Promise but not returning an actual Promise

  • Node.js - 8.11.4
  • npm - 6.9.0
  • request-promise-native : ^1.0.7

request(/*url*/) Has then and catch blocks but it's not an actual Promise instance. It returns Request.

Node.js log:

> const rq = require("request-promise-native")
undefined
> const axios = require('axios')
undefined
> (rq("https://google.com") instanceof Promise)
false
> (rq("https://google.com").then() instanceof Promise)
true
> (axios("https://google.com") instanceof Promise)
true

How to catch the response object?

It seems like right now I can do:

  request(someUrl)
  .then(body => {
    // Do something with your body
  })

Where can I handle the response object? I need to access headers, status code, etc

Timeout as a response and not an exception

Hi guys,

I am making an array of request and, if one of them fails with a timeout, I need to be able to treat this as a response and not an exception.

Code:

try{
    ....
    let promises = [];
    for(const i in bodies){  
        promises.push(request({
            method: 'POST',
            uri: 'uri',
            body: bodies[i],
            headers: {
                'Content-Type': 'application/xml; charset=utf-8'
            },
            auth: {
                'user': 'user',
                'pass': 'pass',
                'sendImmediately': true
            },
            resolveWithFullResponse: true,
            simple: false
        }))
    }

    let reply = await Promise.all(promises)
    ....
}catch(err){
    console.log(err)
}

This code works fine with request-promise lib. What am I missing here?

Thanks

Cannot find module 'request'/'form-data'

The Problem

I'm building a package that depends on request-promise-native. When I try to compile, I'm getting the following errors on the console:

6 import request = require('request');
                           ~~~~~~~~~

node_modules/@types/request-promise-native/index.d.ts(6,26): error TS2307: Cannot find module 'request'.


15 import FormData = require('form-data');
                             ~~~~~~~~~~~

node_modules/@types/request/index.d.ts(15,27): error TS2307: Cannot find module 'form-data'.

I can't figure out why this is happening or how to make these errors go away.

Implementation Details

Here are the relevant bits from package.json:

{
  "devDependencies": {
    "@types/request": "0.0.33",
    "@types/request-promise-native": "^1.0.2"
  },
  "dependencies": {
    "request": "^2.78.0",
    "request-promise-native": "^1.0.3"
  }
}

Here is my tsconfig.json:

{
    "compilerOptions": {
        "module": "es6",
        "target": "es6",
        "declaration": true,
        "declarationDir": "dist",
        "noImplicitAny": true,
        "suppressImplicitAnyIndexErrors": true,
        "noImplicitReturns": true,
        "pretty": true,
        "removeComments": true
    },
    "include": [
        "src/**/*.ts"
    ]
}

And here is an example of how I'm using rpn in my code:

let rp = require('request-promise-native');

interface MyInterface {
    // interface definitinon...
}

class MyClass {
    static async getSomething(param: string): Promise<MyInterface> {
        return await rp({
            uri: "http://placetogetsomething.com",
            qs: { param: param },
            json: true
        }).then(
            (result: any): MyInterface => result,
            (error:  any): MyInterface => { throw Error(error.error_message); }
        );
    }
}

I'm positive that both the request and form-data packages are installed in node_modules. Their type definitions are also installed in node_modules/@types. FWIW, when I tried this with request-promise I also got an error saying that Bluebird was not being found. I'm under the impression that @andy-ms and others from Microsoft are maintaining the type definitions for this package, so I'm a little puzzled as to why I'm getting this error. FYI, I'm using typescript v2.0.9. Thanks!

Targeted catch blocks

Is it possible to use targeted catch blocks as it is with request-promise?

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

rp('http://google.com')
.catch(errors.StatusCodeError, function (reason) {
// The server responded with a status codes other than 2xx.
// Check reason.statusCode
})
.catch(errors.RequestError, function (reason) {
// The request failed due to technical reasons.
// reason.cause is the Error object Request would pass into a callback.
});

When I use

var errors = require('request-promise-native/errors');

I am getting the following error

TypeError: Cannot set property 'name' of undefined
at StatusCodeError (/Users/mirene/Projects/Google/test/request-test/node_modules/request-promise-core/lib/errors.js:24:15)
at
at process._tickCallback (internal/process/next_tick.js:188:7)

Any ideas?

Request Hangs When Setting Body

Request Version:
"request": "^2.81.0",
"request-promise-native": "^1.0.3",

Node Version: 7.8.0

During a Unit Test, I'm using request-promise-native to activate a server method that I'm developing. The request is performed as below:

it("should return 400 when the body doesn't comply with the schema", () => {
	let options: request.RequestPromiseOptions = {
		method: "POST",
		resolveWithFullResponse: true,
		// body: { error: "invalid body" },
		json: true,
	};

	return request("http://localhost:9999/mockpost", options).should.eventually.have.property("statusCode", 400);
});

If I uncomment the body line, the test times out. I've debugged the lib and stepped into the code, but couldn't find the issue - certainly isn't something as simple as stringifying the body.

One thing of note is that the same node process is hosting the server and the client, which may be causing the mess. (of course, request's own tests does that without any problem).

I did not find the localAdress attribute in the native HTTP module.

const http = require('http');
const options = {
host: 'nodejs.cn',
};
const req = http.get(options);
req.end();
req.once('response', (res) => {
const ip = req.socket.localAddress;
const port = req.socket.localPort;
console.log(你的IP地址是 ${ip},你的源端口是 ${port}。);
// consume response object
});

In native HTTP module, req.socket.localAddress can get the IP used by the current connection of the machine, but this attribute is not found in your module.

"Attempted to add script that was already added"

I am receiving the following error message when trying to run MathJax-Node-Sre (which includes this package):

Attempting to add script that was already added [path-to-node_modules]/node_modules/tough_cookie/lib/cookie.js

I have determined that it is this package that is causing the problem by deleting the likely culprits until I received runtime errors instead of build errors.

In particular, I think it is this line in rp.js:

// Load Request freshly - so that users can require an unaltered request instance!
var request = stealthyRequire(require.cache, function () {
    return require('request');
},
function () {
    require('tough-cookie');
}, module);

Somehow, tough-cookie is being required twice. Is anybody else having this issue?

Cannot install on node 6

request-promise-native cannot be installed on Node 6 due to this issue in tough-cookie salesforce/tough-cookie#140

Seems like they are still solving it, but did not release the package with a fix yet.

Solution will be to downgrade dependency to tough-cookie:2.5.0 until the issue with 3.0.0 release is resolved.

No matching version found for [email protected]

the version is not valid, the latest version of request-promise-core is 1.1.1 guess they did something there can you change the package json to take the version with hat^ i will also report this bug at there git repo but now all my builds are failing

Cannot read property 'prototype' of undefined

I am using DialogFlow(previously Api.ai) and creating webhooks to make service calls.I am using the request-promise-native library to make HTTP Post request.When i executed the code locally in my workstation,it worked great.So i used the same code in DialogFlow inline editor .First it prompted me to add request as a dependency.After adding it,I'm getting this error

The deployment of your Cloud Function failed: Function load error: Code in file index.js can't be loaded. Is there a syntax error in your code? Detailed stack trace: TypeError: Cannot read property 'prototype' of undefined at module.exports (/user_code/node_modules/request-promise-native/node_modules/request-promise-core/configure/request2.js:34:47) at Object.<anonymous> (/user_code/node_modules/request-promise-native/lib/rp.js:15:1) at Module._compile (module.js:577:32) at Object.Module._extensions..js (module.js:586:10) at Module.load (module.js:494:32) at tryModuleLoad (module.js:453:12) at Function.Module._load (module.js:445:3) at Module.require (module.js:504:17) at require (internal/module.js:20:19) at Object.<anonymous> (/user_code/index.js:10:10)

My local workstation node js version is v9.11.1 .I tried specifying the same version in DialogFlow package.json 's Node JS version.Here's my package.json

{ "name": "dialogflowFirebaseFulfillment", "description": "This is the default fulfillment for a Dialogflow agents using Cloud Functions for Firebase", "version": "0.0.1", "private": true, "license": "Apache Version 2.0", "author": "Google Inc.", "engines": { "node": "v9.11.1" }, "scripts": { "start": "firebase serve --only functions:dialogflowFirebaseFulfillment", "deploy": "firebase deploy --only functions:dialogflowFirebaseFulfillment" }, "dependencies": { "actions-on-google": "2.0.0-alpha.4", "firebase-admin": "^4.2.1", "firebase-functions": "^0.5.7", "dialogflow": "^0.1.0", "dialogflow-fulfillment": "0.3.0-beta.3", "request-promise-native":"v1.0.5", "request":"^1.0.5", "async":"2.6.1" } }

But still no luck.Any help would be very deeply appreciated.I really need this module to work in my dialogflow.

is there a way to debug and view the raw request?

I have a very simple request with basic http authorization that works in postman and doesn't work via this module. I verified that the header that I'm passing in is exactly the same. Is there a way to see the raw http request and compare the one from postman?

Just a question

Hi Team,
Request is very useful library that have a thousand dependence on npm. Thanks for your work hard and keep the library up to date.

I saw sine v1.0.4 the library started using psl that grew the size of this library from 6.1 kb to 140.1 kb. Could you share the reason? Sorry just a curious question.

here is the chart https://bundlephobia.com/result?p=request-promise-native

Needs to be deprecated in NPM

request gives a deprecated warning when installing through NPM:

fisherj-a01:testDeprecatedNPMPackages fisherj$ npm install request
npm WARN deprecated [email protected]: request has been deprecated, see https://github.com/request/request/issues/3142
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN [email protected] No description
npm WARN [email protected] No repository field.

+ [email protected]
added 47 packages from 58 contributors in 4.222s

but request-promise-native does not:

fisherj-a01:testDeprecatedNPMPackages fisherj$ npm install request-promise-native
npm WARN [email protected] No description
npm WARN [email protected] No repository field.

+ [email protected]
added 4 packages from 3 contributors in 1.331s

We should deprecate the package in NPM to give more ways for people to know.

Thanks!

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.