0.1.0 • Published 10 years ago
@request/core v0.1.0
@request/core
HTTP Duplex Streams2 client. By default it behaves identically to Node's Core http.request method.
Each additional feature must be enabled explicitly via option. Some options requires additional dependencies.
Options
URL
url/uri
Stringurl.Url
qs
ObjectString
Body
form
ObjectStringpass URL encoded string if you want it to be RFC3986 encoded prior sending
json
Object
body
StreamBufferStringArray
multipart - requires @request/multipart
Pass Object for multipart/form-data body:
// set item
multipart: {photo: fs.createReadStream('cat.png')}
// pass additional info about the uploaded item
multipart: {
photo: {
value: fs.createReadStream('cat.png'),
options: {filename: 'cat.png', contentType: 'image/png', knownLength: 22025}
}
}
// pass array of values for this item
multipart: {attachments: [fs.createReadStream('cat.png'), fs.createReadStream('dog.png')]}The item's value can be either: Stream, Request, Buffer or String.
Pass Array for any other multipart/[TYPE], defaults to multipart/related:
// Example: Upload image to Google Drive
multipart: [
{
'Content-Type': 'application/json',
body: JSON.stringify({title: 'cat.png'})
},
{
'Content-Type': 'image/png',
body: fs.createReadStream('cat.png')
}
]The body key is required and reserved for setting up the item's body. It can be either: Stream, Request, Buffer or String.
Additionally you can set preambleCRLF and/or postambleCRLF to true.
Authentication
auth - digest auth requires @request/digest
{user: '', pass: '', sendImmediately: false}- Sets the
Authorization: Basic ...header. - The
sendImmediatelyoption default totrueif omitted. - The
sendImmediately: falseoptions requires the redirect option to be enabled. - Digest authentication requires the @request/digest module.
- Sets the
{bearer: '', sendImmediately: false}- Alternatively the
Authorization: Bearer ...header can be set if using thebeareroption. - The rules for the
sendImmediatelyoption from above applies here.
- Alternatively the
oauth - requires @request/oauth
hawk - requires hawk
httpSignature - requires http-signature
aws - requires aws-sign2
Modifiers
gzip
gzip: true- Pipes the response body to zlib Inflate or Gunzip stream based on the compression method specified in the
content-encodingresponse header.
- Pipes the response body to zlib Inflate or Gunzip stream based on the compression method specified in the
gzip: 'gzip'|gzip: 'deflate'- Explicitly specify which decompression method to use.
encoding - requires iconv-lite
encoding: true- Pipes the response body to iconv-lite stream, defaults to
utf8.
- Pipes the response body to iconv-lite stream, defaults to
encoding: 'ISO-8859-1'|encoding: 'win1251'| ...- Specific encoding to use.
encoding: 'binary'- Set
encodingto'binary'when expecting binary response.
- Set
Misc
cookie - requires tough-cookie
truenew require('tough-cookie).CookieJar(store, options)
length
truedefaults tofalseif omitted
callback
buffers the response body
function(err, res, body)by default the response buffer is decoded into string usingutf8. Set theencodingproperty tobinaryif you expect binary data, or any other specific encoding
redirect
truefollow redirects forGET,HEAD,OPTIONSandTRACErequestsObject- all follow all redirects
- max maximum redirects allowed
- removeReferer remove the
refererheader on redirect - allow
function (res)user defined function to check if the redirect should be allowed
timeout
Numberinteger containing the number of milliseconds to wait for a server to send response headers (and start the response body) before aborting the request. Note that if the underlying TCP connection cannot be established, the OS-wide TCP connection timeout will overrule the timeout option
proxy
Stringurl.UrlObject
{
proxy: 'http://localhost:6767'
//
proxy: url.parse('http://localhost:6767')
//
proxy: {
url: 'http://localhost:6767',
headers: {
allow: ['header-name'],
exclusive: ['header-name']
}
}
}tunnel - requires tunnel-agent
true
parse
{json: true}- sets the
accept: application/jsonheader for the request - parses
JSONorJSONPresponse bodies (only if the server responds with the approprite headers)
- sets the
{json: function () {}}- same as above but additionally passes a user defined reviver function to the
JSON.parsemethod
- same as above but additionally passes a user defined reviver function to the
{qs: {sep:';', eq:':'}}qs.parseoptions to use
{querystring: {sep:';', eq:':', options: {}}}use the querystring module insteadquerystring.parseoptions to use
stringify
{qs: {sep:';', eq:':'}}qs.stringifyoptions to use
{querystring: {sep:';', eq:':', options: {}}}use the querystring module insteadquerystring.stringifyoptions to use
end
truetries to automatically end the request onnextTick
HTTPDuplex
Private Flags and State
_initializedset when the outgoing HTTP request is fully initialized_startedset after first write/end_reqhttp.ClientRequest created in HTTPDuplex_reshttp.IncomingMessage created in HTTPDuplex_clienthttp or https module_redirectboolean indicating that the client is going to be redirected_redirectedboolean indicating that the client is been redirected at least once_srcthe input read stream, usually from pipe_chunksArray - the first chunk read from the input read stream_endedwhether the outgoing request has ended_authwhether basic auth is being used_timeouttimeout timer instance
Public Methods
initabort
Request
Methods
- Request the HTTPDuplex child class
Events
- init should be private I guess
- request req, options
- onresponse res - internal event to execute options response logic
- redirect res
- response res
- options emit @request/core options
- body emit raw response body, either
BufferorString(thecallbackoption is required) - json emit parsed JSON response body (the
callbackand theparse:{json:true}options are required)
req/res
- headers is instance of the @request/headers module
Generated Options
- url contains the parsed URL
- redirect is converted to object containing all possible options including the
followedstate variable, containing the followed redirects count - auth containes
sentstate variable indicating whether the Basic auth is sent already - cookie is converted to object and containes the initial cookie
headeras a property - jar the internal tough-cookie jar
Logger
Requires @request/log
- req prints out the request
method,url, andheaders - res prints out the response
statusCode,statusMessage, andheaders - http prints out the options object passed to the underlying
http.requestmethod - raw prints out the raw
@request/coreoptions object right before sending the request - body prints out the raw request and response bodies (the response body is available only when the
callbackoption is being used) - json prints out the parsed JSON response body (only if the response body is a JSON one, and if the
callbackandparse.jsonoptions are being used)
$ DEBUG=req,res node app.jsErrors
oauth
oauth: transport_method: body requires method: POST and content-type: application/x-www-form-urlencodedoauth: signature_method: PLAINTEXT not supported with body_hash signing
Notice
This module may contain code snippets initially implemented in request by request contributors.
0.1.0
10 years ago