25,479
stars
+-3+-4+-10
3,133
forks
–
watchers
–
prs
–
issues
–
releases
–
discussions
README
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
- Promises & Async/Await
- Forms
- HTTP Authentication
- Custom HTTP Headers
- OAuth Signing
- Proxies
- Unix Domain Sockets
- TLS/SSL Protocol
- Support for HAR 1.2
- All Available Options
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.
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, head