Gathering detailed insights and metrics for @cypress/request-promise
Gathering detailed insights and metrics for @cypress/request-promise
Gathering detailed insights and metrics for @cypress/request-promise
Gathering detailed insights and metrics for @cypress/request-promise
The simplified HTTP request client 'request' with Promise support. Powered by Bluebird.
npm install @cypress/request-promise
Typescript
Module System
Min. Node Version
Node Version
NPM Version
90
Supply Chain
90.9
Quality
70.8
Maintenance
50
Vulnerability
97.9
License
JavaScript (100%)
Total Downloads
4,044,232
Last Day
12,376
Last Week
112,070
Last Month
433,419
Last Year
3,200,351
ISC License
1 Stars
317 Commits
2 Forks
1 Watchers
14 Branches
14 Contributors
Updated on Sep 22, 2023
Minified
Minified + Gzipped
Latest Version
5.0.0
Package Id
@cypress/request-promise@5.0.0
Unpacked Size
37.40 kB
Size
11.81 kB
File Count
6
NPM Version
8.19.2
Node Version
18.12.1
Published on
Aug 24, 2023
Cumulative downloads
Total Downloads
Last Day
-0.9%
12,376
Compared to previous day
Last Week
2.5%
112,070
Compared to previous week
Last Month
15.8%
433,419
Compared to previous month
Last Year
374.5%
3,200,351
Compared to previous year
As of Feb 11th 2020, request
is fully deprecated. No new changes are expected to land. In fact, none have landed for some time. This package is also deprecated because it depends on request
.
Fyi, here is the reasoning of request
's deprecation and a list of alternative libraries.
The simplified HTTP request client 'request' with Promise support. Powered by Bluebird.
Request and Bluebird are pretty awesome, but I found myself using the same design pattern. Request-Promise adds a Bluebird-powered .then(...)
method to Request call objects. By default, http response codes other than 2xx will cause the promise to be rejected. This can be overwritten by setting options.simple = false
.
Also check out the new libraries that are very similar to request-promise
v4:
request-promise-native
v1 – Does not depend on Bluebird and uses native ES6 promises instead.request-promise-any
v1 – Allows you to register any Promise library supported by any-promise
.request
became a peer dependency. Thus make sure that request
is installed into your project as a direct dependency. (npm install --save request
)request-promise-any
.transform
function to v3 and had to add if (!(/^2/.test('' + response.statusCode))) { return resolveWithFullResponse ? response : body; }
you may now set the option transform2xxOnly = true
instead.The handling of the transform
function got overhauled. This has two effects:
StatusCodeError.response
is the transformed instead of the original response now. This error is thrown for non-2xx responses when options.simple
is true
(default). Please update your transform
functions to also cover the transformation of non-2xx responses. To get the old behavior you may add if (!(/^2/.test('' + response.statusCode))) { return resolveWithFullResponse ? response : body; }
to the first line of your transform
functions that are used for requests with options.simple === true
. However, you may prefer updating your transform
functions to being able to transform 2xx as well as non-2xx responses because this decouples their implementation from the use of the simple
option when doing requests.TransformError
. Its cause
attribute contains the error thrown by the transform operation. Previously, the request was rejected directly with the error thrown by the transform operation. Wrapping it into a TransformError
makes the error handling easier.Bluebird got updated from v2 to v3. This won't make a difference for most use cases. However, if you use advanced Promise chains starting with the Promise returned by Request-Promise, please check Bluebird's new features and changes.
This module is installed via npm:
npm install --save request
npm install --save request-promise
request
is defined as a peer-dependency and thus has to be installed separately.
1var rp = require('request-promise');
Since request-promise
wraps around request
everything that works with request
also works with request-promise
. Also check out the request
docs for more examples.
1rp('http://www.google.com') 2 .then(function (htmlString) { 3 // Process html... 4 }) 5 .catch(function (err) { 6 // Crawling failed... 7 });
1var cheerio = require('cheerio'); // Basically jQuery for node.js 2 3var options = { 4 uri: 'http://www.google.com', 5 transform: function (body) { 6 return cheerio.load(body); 7 } 8}; 9 10rp(options) 11 .then(function ($) { 12 // Process html like you would with jQuery... 13 }) 14 .catch(function (err) { 15 // Crawling failed or Cheerio choked... 16 });
1var options = { 2 uri: 'https://api.github.com/user/repos', 3 qs: { 4 access_token: 'xxxxx xxxxx' // -> uri + '?access_token=xxxxx%20xxxxx' 5 }, 6 headers: { 7 'User-Agent': 'Request-Promise' 8 }, 9 json: true // Automatically parses the JSON string in the response 10}; 11 12rp(options) 13 .then(function (repos) { 14 console.log('User has %d repos', repos.length); 15 }) 16 .catch(function (err) { 17 // API call failed... 18 });
Set option.body
to your data and json: true
to encode the body as JSON. See below for HTML forms.
1var options = { 2 method: 'POST', 3 uri: 'http://api.posttestserver.com/post', 4 body: { 5 some: 'payload' 6 }, 7 json: true // Automatically stringifies the body to JSON 8}; 9 10rp(options) 11 .then(function (parsedBody) { 12 // POST succeeded... 13 }) 14 .catch(function (err) { 15 // POST failed... 16 });
Pass your data to options.form
to encode the body the same way as HTML forms do:
1var options = { 2 method: 'POST', 3 uri: 'http://posttestserver.com/post.php', 4 form: { 5 // Like <input type="text" name="name"> 6 name: 'Josh' 7 }, 8 headers: { 9 /* 'content-type': 'application/x-www-form-urlencoded' */ // Is set automatically 10 } 11}; 12 13rp(options) 14 .then(function (body) { 15 // POST succeeded... 16 }) 17 .catch(function (err) { 18 // POST failed... 19 });
If you want to include a file upload then use options.formData
:
1var options = { 2 method: 'POST', 3 uri: 'http://posttestserver.com/post.php', 4 formData: { 5 // Like <input type="text" name="name"> 6 name: 'Jenn', 7 // Like <input type="file" name="file"> 8 file: { 9 value: fs.createReadStream('test/test.jpg'), 10 options: { 11 filename: 'test.jpg', 12 contentType: 'image/jpg' 13 } 14 } 15 }, 16 headers: { 17 /* 'content-type': 'multipart/form-data' */ // Is set automatically 18 } 19}; 20 21rp(options) 22 .then(function (body) { 23 // POST succeeded... 24 }) 25 .catch(function (err) { 26 // POST failed... 27 });
1var tough = require('tough-cookie');
2
3// Easy creation of the cookie - see tough-cookie docs for details
4let cookie = new tough.Cookie({
5 key: "some_key",
6 value: "some_value",
7 domain: 'api.mydomain.com',
8 httpOnly: true,
9 maxAge: 31536000
10});
11
12// Put cookie in an jar which can be used across multiple requests
13var cookiejar = rp.jar();
14cookiejar.setCookie(cookie, 'https://api.mydomain.com');
15// ...all requests to https://api.mydomain.com will include the cookie
16
17var options = {
18 uri: 'https://api.mydomain.com/...',
19 jar: cookiejar // Tells rp to include cookies in jar that match uri
20};
21
22rp(options)
23 .then(function (body) {
24 // Request succeeded...
25 })
26 .catch(function (err) {
27 // Request failed...
28 });
1var options = { 2 method: 'DELETE', 3 uri: 'http://my-server/path/to/resource/1234', 4 resolveWithFullResponse: true // <--- <--- <--- <--- 5}; 6 7rp(options) 8 .then(function (response) { 9 console.log("DELETE succeeded with status %d", response.statusCode); 10 }) 11 .catch(function (err) { 12 // Delete failed... 13 });
1var options = { 2 uri: 'http://www.google.com/this-page-does-not-exist.html', 3 simple: false // <--- <--- <--- <--- 4}; 5 6rp(options) 7 .then(function (body) { 8 // Request succeeded but might as well be a 404 9 // Usually combined with resolveWithFullResponse = true to check response.statusCode 10 }) 11 .catch(function (err) { 12 // Request failed due to technical reasons... 13 });
For more options checkout the Request docs.
Consider Request-Promise being:
require('request-promise') == require('request')
so to say.pipe(...)
) is DISCOURAGED because Request-Promise would grow the memory footprint for large requests unnecessarily high. Use the original Request library for that. You can use both libraries in the same project.rp(...).then(...)
or e.g. rp.post(...).then(...)
which turn rp(...)
and rp.post(...)
into promisesrp(...).catch(...)
or e.g. rp.del(...).catch(...)
which is the same method as provided by Bluebird promises
request
library would pass to the callback are wrapped by request-promise
and then passed to the catch handler. See code example below.rp(...).finally(...)
or e.g. rp.put(...).finally(...)
which is the same method as provided by Bluebird promisesrp(...).cancel()
or e.g. rp.get(...).cancel()
which cancels the requestrp(...).promise()
or e.g. rp.head(...).promise()
which returns the underlying promise so you can access the full Bluebird APIsimple = true
which is a boolean to set whether status codes other than 2xx should also reject the promiseresolveWithFullResponse = false
which is a boolean to set whether the promise should be resolved with the full response or just the response bodytransform
which takes a function to transform the response into a custom value with which the promise is resolvedtransform2xxOnly = false
which is a boolean to set whether the transform function is applied to all responses or only to those with a 2xx status codeThe objects returned by request calls like rp(...)
or e.g. rp.post(...)
are regular Promises/A+ compliant promises and can be assimilated by any compatible promise library.
The methods .then(...)
, .catch(...)
, and .finally(...)
- which you can call on the request call objects - return a full-fledged Bluebird promise. That means you have the full Bluebird API available for further chaining. E.g.: rp(...).then(...).spread(...)
If, however, you need a method other than .then(...)
, .catch(...)
, or .finally(...)
to be FIRST in the chain, use .promise()
: rp(...).promise().bind(...).then(...)
1// As a Request user you would write: 2var request = require('request'); 3 4request('http://google.com', function (err, response, body) { 5 if (err) { 6 handleError({ error: err, response: response, ... }); 7 } else if (!(/^2/.test('' + response.statusCode))) { // Status Codes other than 2xx 8 handleError({ error: body, response: response, ... }); 9 } else { 10 process(body); 11 } 12}); 13 14// As a Request-Promise user you can now write the equivalent code: 15var rp = require('request-promise'); 16 17rp('http://google.com') 18 .then(process, handleError);
1// The same is available for all http method shortcuts: 2request.post('http://example.com/api', function (err, response, body) { ... }); 3rp.post('http://example.com/api').then(...);
1rp('http://google.com') 2 .catch(handleError); 3 4// ... is syntactical sugar for: 5 6rp('http://google.com') 7 .then(null, handleError); 8 9 10// However, this: 11rp('http://google.com') 12 .then(process) 13 .catch(handleError); 14 15// ... is safer than: 16rp('http://google.com') 17 .then(process, handleError);
For more info on .then(process).catch(handleError)
versus .then(process, handleError)
, see Bluebird docs on promise anti-patterns.
1rp('http://google.com') 2 .finally(function () { 3 // This is called after the request finishes either successful or not successful. 4 });
This method cancels the request using Bluebird's cancellation feature.
When .cancel()
is called:
In order to not pollute the Request call objects with the methods of the underlying Bluebird promise, only .then(...)
, .catch(...)
, and .finally(...)
were exposed to cover most use cases. The effect is that any methods of a Bluebird promise other than .then(...)
, .catch(...)
, or .finally(...)
cannot be used as the FIRST method in the promise chain:
1// This works: 2rp('http://google.com').then(function () { ... }); 3rp('http://google.com').catch(function () { ... }); 4 5// This works as well since additional methods are only used AFTER the FIRST call in the chain: 6rp('http://google.com').then(function () { ... }).spread(function () { ... }); 7rp('http://google.com').catch(function () { ... }).error(function () { ... }); 8 9// Using additional methods as the FIRST call in the chain does not work: 10// rp('http://google.com').bind(this).then(function () { ... }); 11 12// Use .promise() in these cases: 13rp('http://google.com').promise().bind(this).then(function () { ... });
resolveWithFullResponse
option1// Per default the body is passed to the fulfillment handler: 2rp('http://google.com') 3 .then(function (body) { 4 // Process the html of the Google web page... 5 }); 6 7// The resolveWithFullResponse options allows to pass the full response: 8rp({ uri: 'http://google.com', resolveWithFullResponse: true }) 9 .then(function (response) { 10 // Access response.statusCode, response.body etc. 11 }); 12
simple
option1// The rejection handler is called with a reason object... 2rp('http://google.com') 3 .catch(function (reason) { 4 // Handle failed request... 5 }); 6 7// ... and would be equivalent to this Request-only implementation: 8var options = { uri: 'http://google.com' }; 9 10request(options, function (err, response, body) { 11 var reason; 12 if (err) { 13 reason = { 14 cause: err, 15 error: err, 16 options: options, 17 response: response 18 }; 19 } else if (!(/^2/.test('' + response.statusCode))) { // Status Codes other than 2xx 20 reason = { 21 statusCode: response.statusCode, 22 error: body, 23 options: options, 24 response: response 25 }; 26 } 27 28 if (reason) { 29 // Handle failed request... 30 } 31}); 32 33 34// If you pass the simple option as false... 35rp({ uri: 'http://google.com', simple: false }) 36 .catch(function (reason) { 37 // Handle failed request... 38 }); 39 40// ... the equivalent Request-only code would be: 41request(options, function (err, response, body) { 42 if (err) { 43 var reason = { 44 cause: err, 45 error: err, 46 options: options, 47 response: response 48 }; 49 // Handle failed request... 50 } 51}); 52// E.g. a 404 would now fulfill the promise. 53// Combine it with resolveWithFullResponse = true to check the status code in the fulfillment handler.
With version 0.4 the reason objects became Error objects with identical properties to ensure backwards compatibility. These new Error types allow targeted catch blocks:
1var errors = require('request-promise/errors'); 2 3rp('http://google.com') 4 .catch(errors.StatusCodeError, function (reason) { 5 // The server responded with a status codes other than 2xx. 6 // Check reason.statusCode 7 }) 8 .catch(errors.RequestError, function (reason) { 9 // The request failed due to technical reasons. 10 // reason.cause is the Error object Request would pass into a callback. 11 });
transform
functionYou can pass a function to options.transform
to generate a custom fulfillment value when the promise gets resolved.
1// Just for fun you could reverse the response body: 2var options = { 3 uri: 'http://google.com', 4 transform: function (body, response, resolveWithFullResponse) { 5 return body.split('').reverse().join(''); 6 } 7}; 8 9rp(options) 10 .then(function (reversedBody) { 11 // ;D 12 }); 13 14 15// However, you could also do something useful: 16var $ = require('cheerio'); // Basically jQuery for node.js 17 18function autoParse(body, response, resolveWithFullResponse) { 19 // FIXME: The content type string could contain additional values like the charset. 20 // Consider using the `content-type` library for a robust comparison. 21 if (response.headers['content-type'] === 'application/json') { 22 return JSON.parse(body); 23 } else if (response.headers['content-type'] === 'text/html') { 24 return $.load(body); 25 } else { 26 return body; 27 } 28} 29 30options.transform = autoParse; 31 32rp(options) 33 .then(function (autoParsedBody) { 34 // :) 35 }); 36 37 38// You can go one step further and set the transform as the default: 39var rpap = rp.defaults({ transform: autoParse }); 40 41rpap('http://google.com') 42 .then(function (autoParsedBody) { 43 // :) 44 }); 45 46rpap('http://echojs.com') 47 .then(function (autoParsedBody) { 48 // =) 49 });
The third resolveWithFullResponse
parameter of the transform function is equivalent to the option passed with the request. This allows to distinguish whether just the transformed body or the whole response shall be returned by the transform function:
1function reverseBody(body, response, resolveWithFullResponse) { 2 response.body = response.body.split('').reverse().join(''); 3 return resolveWithFullResponse ? response : response.body; 4}
As of Request-Promise v3 the transform function is ALWAYS executed for non-2xx responses. When options.simple
is set to true
(default) then non-2xx responses are rejected with a StatusCodeError
. In this case the error contains the transformed response:
1var options = { 2 uri: 'http://the-server.com/will-return/404', 3 simple: true, 4 transform: function (body, response, resolveWithFullResponse) { /* ... */ } 5}; 6 7rp(options) 8 .catch(errors.StatusCodeError, function (reason) { 9 // reason.response is the transformed response 10 });
You may set options.transform2xxOnly = true
to only execute the transform function for responses with a 2xx status code. For other status codes – independent of any other settings, e.g. options.simple
– the transform function is not executed.
If the transform operation fails (throws an error) the request will be rejected with a TransformError
:
1var errors = require('request-promise/errors'); 2 3var options = { 4 uri: 'http://google.com', 5 transform: function (body, response, resolveWithFullResponse) { 6 throw new Error('Transform failed!'); 7 } 8}; 9 10rp(options) 11 .catch(errors.TransformError, function (reason) { 12 console.log(reason.cause.message); // => Transform failed! 13 // reason.response is the original response for which the transform operation failed 14 });
Continuation Local Storage is no longer supported. However, you can get back the support by using request-promise-any
.
The ways to debug the operation of Request-Promise are the same as described for Request. These are:
NODE_DEBUG=request node script.js
(lib,request,otherlib
works too).require('request-promise').debug = true
at any time (this does the same thing as #1).require('request-debug')(rp);
.Usually you want to mock the whole request function which is returned by require('request-promise')
. This is not possible by using a mocking library like sinon.js alone. What you need is a library that ties into the module loader and makes sure that your mock is returned whenever the tested code is calling require('request-promise')
. Mockery is one of such libraries.
@florianschmidt1994 kindly shared his solution:
1before(function (done) { 2 3 var filename = "fileForResponse"; 4 mockery.enable({ 5 warnOnReplace: false, 6 warnOnUnregistered: false, 7 useCleanCache: true 8 }); 9 10 mockery.registerMock('request-promise', function () { 11 var response = fs.readFileSync(__dirname + '/data/' + filename, 'utf8'); 12 return Bluebird.resolve(response.trim()); 13 }); 14 15 done(); 16}); 17 18after(function (done) { 19 mockery.disable(); 20 mockery.deregisterAll(); 21 done(); 22}); 23 24describe('custom test case', function () { 25 // Test some function/module/... which uses request-promise 26 // and it will always receive the predefined "fileForResponse" as data, e.g.: 27 var rp = require('request-promise'); 28 rp(...).then(function(data) { 29 // ➞ data is what is in fileForResponse 30 }); 31});
Based on that you may now build a more sophisticated mock. Sinon.js may be of help as well.
To set up your development environment:
cd
to the main folder,npm install
,npm install gulp -g
if you haven't installed gulp globally yet, andgulp dev
. (Or run node ./node_modules/.bin/gulp dev
if you don't want to install gulp globally.)gulp dev
watches all source files and if you save some changes it will lint the code and execute all tests. The test coverage report can be viewed from ./coverage/lcov-report/index.html
.
If you want to debug a test you should use gulp test-without-coverage
to run all tests without obscuring the code by the test coverage instrumentation.
request-promise-core
which bumps lodash
to ^4.17.15
. See vulnerabilty reports.
(Thanks to @rishabh-chowdhary for reporting this in pull request #326.)tough-cookie
version, now ^2.3.3
(Thanks to @evocateur for pointing this out.)request-promise@4.2.3
please make sure after the upgrade that request
and request-promise
use the same physical copy of tough-cookie
.tough-cookie@~2.3.3
to avoid installing tough-cookie@3
which introduces breaking changes
(Thanks to @aomdoa for pull request #299)lodash
to ^4.17.11
, see vulnerabilty reportstough-cookie
to a version without regex DoS vulnerability
(Thanks to @rouanw for pull request #226)tough-cookie
for cookie creation
(Thanks to @ScottyMJacobson for reporting issue #183)bluebird
to v3.5
(Thanks to @acinader for pull request #181)@request/promise-core
version for safer versioningrequest
is declared as a peer dependency which has to be installed separately by the user nowrequest-promise-any
can be used for that nowtransform2xxOnly
option to ease the breaking change regarding the new transform
handling in v3.0.0
(Thanks to @stevage for pointing out the effect of the breaking change in issue #131)request-promise-native
and request-promise-any
(Thanks to @benjamingr, @eilgin, @gillesdemey, @hildjj, @iggycoloma, @jonathanong, @knpwrs, @MarkHerhold, @massimocode, @mikeal, @niftylettuce, @raitucarp, @sherdeadlock, @tonylukasavage, and @vgoloviznin for the valuable discussions!)transform
function
(Thanks to @Limess for explaining the need in issue #86)bluebird
to v3
(Thanks to @BrandonSmith for pull request #103)StatusCodeError.message
lodash
to v4.6.catch(...)
best practice
(Thanks to @RebootJeff for pull request #98)lodash
to v4
(Thanks to @ratson for pull request #94)cls-bluebird
dependency which has to be installed by the user now
(Thanks to @hildjj for his pull request #75)npm shrinkwrap
now works for npm@3
users who don't use continuation-local-storage
(Thanks to @toboid and @rstacruz for reporting the issue in issue #70 and issue #82)continuation-local-storage
from peer dependencies as it was unnecessary
(Thanks to @mrhyde for working on a better solution discussed in issue #70)continuation-local-storage
as a peer dependencyresolveWithFullResponse = true
is used)
(Thanks to @zcei for proposing the change in issue #58)transform
function by a third resolveWithFullResponse
parametertypeof reason === 'object'
still holds true and the error objects have the same properties as the previous reason objects. If the reject handler only accesses the properties on the reason object - which is usually the case - no migration is required..finally(...)
to allow using it as the first method in the promise chain
(Thanks to @hjpbarcelos for his pull request #28).promise()
method for advanced Bluebird API usage
(Thanks to @devo-tox for his feedback in issue #27)In case you never heard about the ISC license it is functionally equivalent to the MIT license.
See the LICENSE file for details.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
Found 2/30 approved changesets -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
security policy file not detected
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
44 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-06-23
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More