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







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.
js
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
- [Streaming](#streaming)
- [Promises & Async/Await](#promises--asyncawait)
- [Forms](#forms)
- [HTTP Authentication](#http-authentication)
- [Custom HTTP Headers](#custom-http-headers)
- [OAuth Signing](#oauth-signing)
- [Proxies](#proxies)
- [Unix Domain Sockets](#unix-domain-sockets)
- [TLS/SSL Protocol](#tlsssl-protocol)
- [Support for HAR 1.2](#support-for-har-12)
- [All Available Options](#requestoptions-callback)
request.defaults and request.post, and there are
lots of [usage examples](#examples) and several
[debugging techniques](#debugging).
---
Streaming
You can stream any response to a file stream.
js
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).
js
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.
js
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.
js
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:
js
request
.get('http://mysite.com/doodle.png')
.on('error', function(err) {
console.error(err)
})
.pipe(fs.createWriteStream('doodle.png'))
Now let’s get fancy.
js
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:
js
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. :)
js
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.
js
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](#table-of-contents)
---
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:
request-promise(uses Bluebird Promises)request-promise-native(uses native Promises)request-promise-any(uses any-promise Promises)
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](#table-of-contents)
---
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.
js
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.
js
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.)
js
// 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.
js
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](#table-of-contents)
---
HTTP Authentication
js
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||usernamepass||passwordsendImmediately(optional)bearer(optional)
auth(username, password, sendImmediately, bearer).
sendImmediately defaults to true, which causes a basic or bearer
authentication header to be sent. If sendImmediately is false, thenrequest will retry with a proper authentication header after receiving a401 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 theuser:password before the host with an @ sign:
js
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 aString. 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](#table-of-contents)
---
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.
js
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](#table-of-contents)
---
OAuth Signing
OAuth version 1.0 is supported. The
default signing algorithm is
HMAC-SHA1:
js
// 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 aprivate_keystring in
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](http://oauth.net/core/1.0/#consumer
…
Members
-
request
🏊🏾 Simplified HTTP request client.
JavaScript ★ 26k 1y agoExplain → -
request-promise
The simplified HTTP request client 'request' with Promise support. Powered by Bluebird.
JavaScript ★ 4.7k 2y agoExplain → -
request-promise-native
The simplified HTTP request client 'request' with Promise support. Powered by native ES6 promises.
JavaScript ★ 1.1k 3y agoExplain → -
request-debug
Library to monitor HTTP(S) requests made with mikeal/request.
JavaScript ★ 142 6y agoExplain → -
tunnel-agent
HTTP proxy tunneling agent. Formerly part of mikeal/request, now a standalone module.
JavaScript ★ 118 6y agoExplain → -
caseless
Caseless object set/get/has, very useful when working with HTTP headers.
JavaScript ★ 96 5y agoExplain → -
forever-agent
HTTP Agent that keeps socket connections alive between keep-alive requests. Formerly part of mikeal/request, now a standalone module.
JavaScript ★ 79 6y agoExplain → -
oauth-sign
OAuth 1 signing. Formerly a vendor lib in mikeal/request, now a standalone module.
JavaScript ★ 60 6y agoExplain → -
aws-sign
AWS signing. Originally pulled from LearnBoost/knox, maintained as vendor in request, now a standalone module.
JavaScript ★ 30 6y agoExplain → -
request-promise-any
The simplified HTTP request client 'request' with Promise support. Powered by 'any-promise'.
JavaScript ★ 21 6y agoExplain → -
promise-core
Core Promise support implementation for the simplified HTTP request client 'request'.
JavaScript ★ 20 5y agoExplain → -
cookie-jar
Cookie Jar. Originally pulled from LearnBoost/tobi, maintained as vendor in request, now a standalone module.
JavaScript ★ 10 13y agoExplain → -
interface
Common Interface for HTTP Clients
JavaScript ★ 5 10y agoExplain → -
api
Sugar API for @request/interface consumers
JavaScript ★ 5 6y agoExplain → -
cli
HTTP CLI Client
JavaScript ★ 4 10y agoExplain → -
request.js.org
Official Website of the Request Organization
★ 4 9y agoExplain → -
core
HTTP Client Library
JavaScript ★ 3 8y agoExplain → -
http-duplex-gzip-client
HTTP duplex client that accepts and decompresses gzip.
JavaScript ★ 2 12y agoExplain → -
multipart
HTTP Multipart Body Stream
JavaScript ★ 2 10y agoExplain → -
digest
HTTP Digest Authentication
JavaScript ★ 2 10y agoExplain → -
legacy
No description.
JavaScript ★ 1 9y agoExplain → -
oauth
HTTP OAuth Authentication
JavaScript ★ 1 10y agoExplain → -
log
HTTP Debug Log
JavaScript ★ 1 10y agoExplain → -
length
HTTP Content-Length for various body types
JavaScript ★ 1 10y agoExplain → -
qs
Wrapper for qs and querystring modules
JavaScript ★ 1 10y agoExplain → -
http-duplex-client ⑂
Duplex API for making an HTTP request (write the req, read the response)
JavaScript ★ 1 12y agoExplain → -
client
HTTP Client Library
JavaScript ★ 1 10y agoExplain → -
headers
HTTP Caseless Headers
JavaScript ★ 1 10y agoExplain → -
request-promise-bluebird
DO NOT USE request-promise-bluebird! Use request-promise instead. It uses Bluebird under the hood.
JavaScript ★ 0 10y agoExplain →
No repos match these filters.