Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

request

Package Overview
Dependencies
Maintainers
4
Versions
126
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

request - npm Package Compare versions

Comparing version 2.81.0 to 2.82.0

27

index.js

@@ -17,11 +17,10 @@ // Copyright 2010-2012 Mikeal Rogers

var extend = require('extend')
, cookies = require('./lib/cookies')
, helpers = require('./lib/helpers')
var extend = require('extend')
var cookies = require('./lib/cookies')
var helpers = require('./lib/helpers')
var paramsHaveRequestBody = helpers.paramsHaveRequestBody
// organize params for patch, post, put, head, del
function initParams(uri, options, callback) {
function initParams (uri, options, callback) {
if (typeof options === 'function') {

@@ -70,2 +69,3 @@ callback = options

request.head = verbFunc('head')
request.options = verbFunc('options')
request.post = verbFunc('post')

@@ -86,3 +86,2 @@ request.put = verbFunc('put')

function wrapRequestMethod (method, options, requester, verb) {
return function (uri, opts, callback) {

@@ -118,11 +117,11 @@ var params = initParams(uri, opts, callback)

var defaults = wrapRequestMethod(self, options, requester)
var defaults = wrapRequestMethod(self, options, requester)
var verbs = ['get', 'head', 'post', 'put', 'patch', 'del', 'delete']
verbs.forEach(function(verb) {
defaults[verb] = wrapRequestMethod(self[verb], options, requester, verb)
verbs.forEach(function (verb) {
defaults[verb] = wrapRequestMethod(self[verb], options, requester, verb)
})
defaults.cookie = wrapRequestMethod(self.cookie, options, requester)
defaults.jar = self.jar
defaults.cookie = wrapRequestMethod(self.cookie, options, requester)
defaults.jar = self.jar
defaults.defaults = self.defaults

@@ -153,9 +152,9 @@ return defaults

Object.defineProperty(request, 'debug', {
enumerable : true,
get : function() {
enumerable: true,
get: function () {
return request.Request.debug
},
set : function(debug) {
set: function (debug) {
request.Request.debug = debug
}
})
'use strict'
var caseless = require('caseless')
, uuid = require('uuid')
, helpers = require('./helpers')
var uuid = require('uuid')
var helpers = require('./helpers')
var md5 = helpers.md5
, toBase64 = helpers.toBase64
var toBase64 = helpers.toBase64
function Auth (request) {

@@ -129,3 +128,3 @@ // define all public properties here

var self = this
, request = self.request
var request = self.request

@@ -147,3 +146,3 @@ var authHeader

var self = this
, request = self.request
var request = self.request

@@ -150,0 +149,0 @@ if (!self.hasAuth || self.sentAuth) { return null }

@@ -6,6 +6,5 @@ 'use strict'

var Cookie = tough.Cookie
, CookieJar = tough.CookieJar
var CookieJar = tough.CookieJar
exports.parse = function(str) {
exports.parse = function (str) {
if (str && str.uri) {

@@ -21,15 +20,15 @@ str = str.uri

// Adapt the sometimes-Async api of tough.CookieJar to our requirements
function RequestJar(store) {
function RequestJar (store) {
var self = this
self._jar = new CookieJar(store, {looseMode: true})
}
RequestJar.prototype.setCookie = function(cookieOrStr, uri, options) {
RequestJar.prototype.setCookie = function (cookieOrStr, uri, options) {
var self = this
return self._jar.setCookieSync(cookieOrStr, uri, options || {})
}
RequestJar.prototype.getCookieString = function(uri) {
RequestJar.prototype.getCookieString = function (uri) {
var self = this
return self._jar.getCookieStringSync(uri)
}
RequestJar.prototype.getCookies = function(uri) {
RequestJar.prototype.getCookies = function (uri) {
var self = this

@@ -39,4 +38,4 @@ return self._jar.getCookiesSync(uri)

exports.jar = function(store) {
exports.jar = function (store) {
return new RequestJar(store)
}
'use strict'
function formatHostname(hostname) {
function formatHostname (hostname) {
// canonicalize the hostname, so that 'oogle.com' won't match 'google.com'

@@ -8,9 +8,9 @@ return hostname.replace(/^\.*/, '.').toLowerCase()

function parseNoProxyZone(zone) {
function parseNoProxyZone (zone) {
zone = zone.trim().toLowerCase()
var zoneParts = zone.split(':', 2)
, zoneHost = formatHostname(zoneParts[0])
, zonePort = zoneParts[1]
, hasPort = zone.indexOf(':') > -1
var zoneHost = formatHostname(zoneParts[0])
var zonePort = zoneParts[1]
var hasPort = zone.indexOf(':') > -1

@@ -20,14 +20,14 @@ return {hostname: zoneHost, port: zonePort, hasPort: hasPort}

function uriInNoProxy(uri, noProxy) {
function uriInNoProxy (uri, noProxy) {
var port = uri.port || (uri.protocol === 'https:' ? '443' : '80')
, hostname = formatHostname(uri.hostname)
, noProxyList = noProxy.split(',')
var hostname = formatHostname(uri.hostname)
var noProxyList = noProxy.split(',')
// iterate through the noProxyList until it finds a match.
return noProxyList.map(parseNoProxyZone).some(function(noProxyZone) {
return noProxyList.map(parseNoProxyZone).some(function (noProxyZone) {
var isMatchedAt = hostname.indexOf(noProxyZone.hostname)
, hostnameMatched = (
isMatchedAt > -1 &&
(isMatchedAt === hostname.length - noProxyZone.hostname.length)
)
var hostnameMatched = (
isMatchedAt > -1 &&
(isMatchedAt === hostname.length - noProxyZone.hostname.length)
)

@@ -42,3 +42,3 @@ if (noProxyZone.hasPort) {

function getProxyFromURI(uri) {
function getProxyFromURI (uri) {
// Decide the proper request proxy to use based on the request URI object and the

@@ -66,3 +66,3 @@ // environmental variables (NO_PROXY, HTTP_PROXY, etc.)

return process.env.HTTP_PROXY ||
process.env.http_proxy || null
process.env.http_proxy || null
}

@@ -72,5 +72,5 @@

return process.env.HTTPS_PROXY ||
process.env.https_proxy ||
process.env.HTTP_PROXY ||
process.env.http_proxy || null
process.env.https_proxy ||
process.env.HTTP_PROXY ||
process.env.http_proxy || null
}

@@ -77,0 +77,0 @@

@@ -74,10 +74,6 @@ 'use strict'

'multipart/alternative'])) {
// reset values
data.postData.mimeType = 'multipart/form-data'
}
else if (some([
} else if (some([
'application/x-www-form-urlencoded'])) {
if (!data.postData.params) {

@@ -91,5 +87,3 @@ data.postData.text = ''

}
}
else if (some([
} else if (some([
'text/json',

@@ -99,3 +93,2 @@ 'text/x-json',

'application/x-json'])) {
data.postData.mimeType = 'application/json'

@@ -174,4 +167,3 @@

options.form = req.postData.paramsObj
}
else if (test('application/json')) {
} else if (test('application/json')) {
if (req.postData.jsonObj) {

@@ -181,4 +173,3 @@ options.body = req.postData.jsonObj

}
}
else if (test('multipart/form-data')) {
} else if (test('multipart/form-data')) {
options.formData = {}

@@ -210,4 +201,3 @@

})
}
else {
} else {
if (req.postData.text) {

@@ -214,0 +204,0 @@ options.body = req.postData.text

'use strict'
var jsonSafeStringify = require('json-stringify-safe')
, crypto = require('crypto')
, Buffer = require('safe-buffer').Buffer
var crypto = require('crypto')
var Buffer = require('safe-buffer').Buffer

@@ -11,3 +11,3 @@ var defer = typeof setImmediate === 'undefined'

function paramsHaveRequestBody(params) {
function paramsHaveRequestBody (params) {
return (

@@ -61,8 +61,8 @@ params.body ||

exports.paramsHaveRequestBody = paramsHaveRequestBody
exports.safeStringify = safeStringify
exports.md5 = md5
exports.isReadStream = isReadStream
exports.toBase64 = toBase64
exports.copy = copy
exports.version = version
exports.defer = defer
exports.safeStringify = safeStringify
exports.md5 = md5
exports.isReadStream = isReadStream
exports.toBase64 = toBase64
exports.copy = copy
exports.version = version
exports.defer = defer
'use strict'
var uuid = require('uuid')
, CombinedStream = require('combined-stream')
, isstream = require('isstream')
, Buffer = require('safe-buffer').Buffer
var CombinedStream = require('combined-stream')
var isstream = require('isstream')
var Buffer = require('safe-buffer').Buffer
function Multipart (request) {

@@ -18,4 +17,4 @@ this.request = request

var self = this
, chunked = false
, parts = options.data || options
var chunked = false
var parts = options.data || options

@@ -107,3 +106,3 @@ if (!parts.forEach) {

var chunked = self.isChunked(options)
, parts = options.data || options
var parts = options.data || options

@@ -110,0 +109,0 @@ self.setHeaders(chunked)

'use strict'
var url = require('url')
, qs = require('qs')
, caseless = require('caseless')
, uuid = require('uuid')
, oauth = require('oauth-sign')
, crypto = require('crypto')
, Buffer = require('safe-buffer').Buffer
var qs = require('qs')
var caseless = require('caseless')
var uuid = require('uuid')
var oauth = require('oauth-sign')
var crypto = require('crypto')
var Buffer = require('safe-buffer').Buffer
function OAuth (request) {

@@ -26,3 +25,3 @@ this.request = request

if (!oa.oauth_timestamp) {
oa.oauth_timestamp = Math.floor( Date.now() / 1000 ).toString()
oa.oauth_timestamp = Math.floor(Date.now() / 1000).toString()
}

@@ -36,7 +35,7 @@ if (!oa.oauth_nonce) {

var consumer_secret_or_private_key = oa.oauth_consumer_secret || oa.oauth_private_key
var consumer_secret_or_private_key = oa.oauth_consumer_secret || oa.oauth_private_key // eslint-disable-line camelcase
delete oa.oauth_consumer_secret
delete oa.oauth_private_key
var token_secret = oa.oauth_token_secret
var token_secret = oa.oauth_token_secret // eslint-disable-line camelcase
delete oa.oauth_token_secret

@@ -56,4 +55,5 @@

params,
consumer_secret_or_private_key,
token_secret)
consumer_secret_or_private_key, // eslint-disable-line camelcase
token_secret // eslint-disable-line camelcase
)

@@ -67,3 +67,3 @@ if (realm) {

OAuth.prototype.buildBodyHash = function(_oauth, body) {
OAuth.prototype.buildBodyHash = function (_oauth, body) {
if (['HMAC-SHA1', 'RSA-SHA1'].indexOf(_oauth.signature_method || 'HMAC-SHA1') < 0) {

@@ -103,12 +103,12 @@ this.request.emit('error', new Error('oauth: ' + _oauth.signature_method +

var uri = self.request.uri || {}
, method = self.request.method || ''
, headers = caseless(self.request.headers)
, body = self.request.body || ''
, qsLib = self.request.qsLib || qs
var method = self.request.method || ''
var headers = caseless(self.request.headers)
var body = self.request.body || ''
var qsLib = self.request.qsLib || qs
var form
, query
, contentType = headers.get('content-type') || ''
, formContentType = 'application/x-www-form-urlencoded'
, transport = _oauth.transport_method || 'header'
var query
var contentType = headers.get('content-type') || ''
var formContentType = 'application/x-www-form-urlencoded'
var transport = _oauth.transport_method || 'header'

@@ -115,0 +115,0 @@ if (contentType.slice(0, formContentType.length) === formContentType) {

'use strict'
var qs = require('qs')
, querystring = require('querystring')
var querystring = require('querystring')
function Querystring (request) {

@@ -16,3 +15,3 @@ this.request = request

Querystring.prototype.init = function (options) {
if (this.lib) {return}
if (this.lib) { return }

@@ -19,0 +18,0 @@ this.useQuerystring = options.useQuerystring

@@ -12,3 +12,3 @@ 'use strict'

this.followOriginalHttpMethod = false
this.allowRedirect = function () {return true}
this.allowRedirect = function () { return true }
this.maxRedirects = 10

@@ -48,3 +48,3 @@ this.redirects = []

var self = this
, request = self.request
var request = self.request

@@ -83,3 +83,3 @@ var redirectTo = null

var self = this
, request = self.request
var request = self.request

@@ -118,9 +118,6 @@ var redirectTo = self.redirectTo(response)

self.redirects.push(
{ statusCode : response.statusCode
, redirectUri: redirectTo
}
)
if (self.followAllRedirects && request.method !== 'HEAD'
&& response.statusCode !== 401 && response.statusCode !== 307) {
self.redirects.push({ statusCode: response.statusCode, redirectUri: redirectTo })
if (self.followAllRedirects && request.method !== 'HEAD' &&
response.statusCode !== 401 && response.statusCode !== 307) {
request.method = self.followOriginalHttpMethod ? request.method : 'GET'

@@ -127,0 +124,0 @@ }

'use strict'
var url = require('url')
, tunnel = require('tunnel-agent')
var tunnel = require('tunnel-agent')

@@ -34,6 +34,6 @@ var defaultProxyHeaderWhiteList = [

function constructProxyHost(uriObject) {
function constructProxyHost (uriObject) {
var port = uriObject.port
, protocol = uriObject.protocol
, proxyHost = uriObject.hostname + ':'
var protocol = uriObject.protocol
var proxyHost = uriObject.hostname + ':'

@@ -51,3 +51,3 @@ if (port) {

function constructProxyHeaderWhiteList(headers, proxyHeaderWhiteList) {
function constructProxyHeaderWhiteList (headers, proxyHeaderWhiteList) {
var whiteList = proxyHeaderWhiteList

@@ -73,18 +73,18 @@ .reduce(function (set, header) {

var tunnelOptions = {
proxy : {
host : proxy.hostname,
port : +proxy.port,
proxyAuth : proxy.auth,
headers : proxyHeaders
proxy: {
host: proxy.hostname,
port: +proxy.port,
proxyAuth: proxy.auth,
headers: proxyHeaders
},
headers : request.headers,
ca : request.ca,
cert : request.cert,
key : request.key,
passphrase : request.passphrase,
pfx : request.pfx,
ciphers : request.ciphers,
rejectUnauthorized : request.rejectUnauthorized,
secureOptions : request.secureOptions,
secureProtocol : request.secureProtocol
headers: request.headers,
ca: request.ca,
cert: request.cert,
key: request.key,
passphrase: request.passphrase,
pfx: request.pfx,
ciphers: request.ciphers,
rejectUnauthorized: request.rejectUnauthorized,
secureOptions: request.secureOptions,
secureProtocol: request.secureProtocol
}

@@ -95,3 +95,3 @@

function constructTunnelFnName(uri, proxy) {
function constructTunnelFnName (uri, proxy) {
var uriProtocol = (uri.protocol === 'https:' ? 'https' : 'http')

@@ -102,3 +102,3 @@ var proxyProtocol = (proxy.protocol === 'https:' ? 'Https' : 'Http')

function getTunnelFn(request) {
function getTunnelFn (request) {
var uri = request.uri

@@ -110,3 +110,2 @@ var proxy = request.proxy

function Tunnel (request) {

@@ -123,4 +122,4 @@ this.request = request

var self = this
, request = self.request
// Tunnel HTTPS by default. Allow the user to override this setting.
var request = self.request
// Tunnel HTTPS by default. Allow the user to override this setting.

@@ -143,3 +142,3 @@ // If self.tunnelOverride is set (the user specified a value), use it.

var self = this
, request = self.request
var request = self.request

@@ -146,0 +145,0 @@ options = options || {}

@@ -10,3 +10,3 @@ {

],
"version": "2.81.0",
"version": "2.82.0",
"author": "Mikeal Rogers <mikeal.rogers@gmail.com>",

@@ -31,24 +31,24 @@ "repository": {

"dependencies": {
"aws-sign2": "~0.6.0",
"aws4": "^1.2.1",
"aws-sign2": "~0.7.0",
"aws4": "^1.6.0",
"caseless": "~0.12.0",
"combined-stream": "~1.0.5",
"extend": "~3.0.0",
"extend": "~3.0.1",
"forever-agent": "~0.6.1",
"form-data": "~2.1.1",
"har-validator": "~4.2.1",
"hawk": "~3.1.3",
"http-signature": "~1.1.0",
"form-data": "~2.3.1",
"har-validator": "~5.0.3",
"hawk": "~6.0.2",
"http-signature": "~1.2.0",
"is-typedarray": "~1.0.0",
"isstream": "~0.1.2",
"json-stringify-safe": "~5.0.1",
"mime-types": "~2.1.7",
"oauth-sign": "~0.8.1",
"performance-now": "^0.2.0",
"qs": "~6.4.0",
"safe-buffer": "^5.0.1",
"stringstream": "~0.0.4",
"tough-cookie": "~2.3.0",
"mime-types": "~2.1.17",
"oauth-sign": "~0.8.2",
"performance-now": "^2.1.0",
"qs": "~6.5.1",
"safe-buffer": "^5.1.1",
"stringstream": "~0.0.5",
"tough-cookie": "~2.3.2",
"tunnel-agent": "^0.6.0",
"uuid": "^3.0.0"
"uuid": "^3.1.0"
},

@@ -60,3 +60,3 @@ "scripts": {

"test-browser": "node tests/browser/start.js",
"lint": "eslint lib/ *.js tests/ && echo Lint passed."
"lint": "standard"
},

@@ -68,5 +68,4 @@ "devDependencies": {

"buffer-equal": "^1.0.0",
"codecov": "^1.0.1",
"codecov": "^2.0.2",
"coveralls": "^2.11.4",
"eslint": "^2.5.3",
"function-bind": "^1.0.2",

@@ -83,2 +82,3 @@ "istanbul": "^0.4.0",

"server-destroy": "^1.0.1",
"standard": "^9.0.0",
"tape": "^4.6.0",

@@ -89,3 +89,2 @@ "taper": "^0.5.0"

"ignore": [
"eslint",
"hawk",

@@ -92,0 +91,0 @@ "har-validator"

@@ -31,2 +31,3 @@

- [Streaming](#streaming)
- [Promises & Async/Await](#promises--asyncawait)
- [Forms](#forms)

@@ -146,2 +147,18 @@ - [HTTP Authentication](#http-authentication)

## 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`](https://github.com/request/request-promise) (uses [Bluebird](https://github.com/petkaantonov/bluebird) Promises)
- [`request-promise-native`](https://github.com/request/request-promise-native) (uses native Promises)
- [`request-promise-any`](https://github.com/request/request-promise-any) (uses [any-promise](https://www.npmjs.com/package/any-promise) Promises)
[back to top](#table-of-contents)
---
## Forms

@@ -613,3 +630,3 @@

In the example below, we call an API requires client side SSL certificate
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:

@@ -673,3 +690,3 @@

a validation step will check if the HAR Request format matches the latest spec (v1.2) and will skip parsing if not matching.
A validation step will check if the HAR Request format matches the latest spec (v1.2) and will skip parsing if not matching.

@@ -733,3 +750,3 @@ ```js

- `qsStringifyOptions` - object containing options to pass to the [qs.stringify](https://github.com/hapijs/qs#stringifying) method. Alternatively pass options to the [querystring.stringify](https://nodejs.org/docs/v0.12.0/api/querystring.html#querystring_querystring_stringify_obj_sep_eq_options) 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
- `useQuerystring` - if true, use `querystring` to stringify and parse
querystrings, otherwise use `qs` (default: `false`). Set this option to

@@ -743,3 +760,3 @@ `true` if you need arrays to be serialized as `foo=bar&foo=baz` instead of the

- `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
- `formData` - data to pass for a `multipart/form-data` request. See
[Forms](#forms) section above.

@@ -761,7 +778,7 @@ - `multipart` - array of objects which contain their own headers and `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](https://github.com/hueniverse/hawk). The `credentials` key must contain the necessary signing info, [see hawk docs for details](https://github.com/hueniverse/hawk#usage-example).
- `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](https://github.com/hueniverse/hawk). The `credentials` key must contain the necessary signing info, [see hawk docs for details](https://github.com/hueniverse/hawk#usage-example).
- `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. **Note:** you need to `npm install aws4` first.
- `httpSignature` - Options for the [HTTP Signature Scheme](https://github.com/joyent/node-http-signature/blob/master/http_signing.md) using [Joyent's library](https://github.com/joyent/node-http-signature). The `keyId` and `key` properties must be specified. See the docs for other options.
- `httpSignature` - options for the [HTTP Signature Scheme](https://github.com/joyent/node-http-signature/blob/master/http_signing.md) using [Joyent's library](https://github.com/joyent/node-http-signature). The `keyId` and `key` properties must be specified. See the docs for other options.

@@ -778,5 +795,5 @@ ---

- `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](http://nodejs.org/api/buffer.html#buffer_buffer) 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)
- `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](http://nodejs.org/api/buffer.html#buffer_buffer) 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)

@@ -789,3 +806,3 @@ ---

- `forever` - set to `true` to use the [forever-agent](https://github.com/request/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.
- `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}`).

@@ -797,3 +814,3 @@ - Note that if you are sending multiple requests in a loop and creating

property outside of the loop.
- `timeout` - Integer containing the number of milliseconds to wait for a
- `timeout` - integer containing the number of milliseconds to wait for a
server to send response headers (and start the response body) before aborting

@@ -808,5 +825,5 @@ the request. Note that if the underlying TCP connection cannot be established,

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

@@ -819,5 +836,5 @@ [HTTP `CONNECT` tunneling](https://en.wikipedia.org/wiki/HTTP_tunnel#HTTP_CONNECT_tunneling)

- `false` - request the destination as a `GET` request.
- `proxyHeaderWhiteList` - A whitelist of headers to send to a
- `proxyHeaderWhiteList` - a whitelist of headers to send to a
tunneling proxy.
- `proxyHeaderExclusiveList` - A whitelist of headers to send
- `proxyHeaderExclusiveList` - a whitelist of headers to send
exclusively to a tunneling proxy and not to destination.

@@ -827,3 +844,3 @@

- `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:
- `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*).

@@ -846,3 +863,3 @@ - `responseStartTime` Timestamp when the response began (in Unix Epoch milliseconds) (*deprecated*).

- `har` - A [HAR 1.2 Request Object](http://www.softwareishard.com/blog/har-12-spec/#request), will be processed from HAR format into options overwriting matching values *(see the [HAR 1.2 section](#support-for-har-1.2) for details)*
- `har` - a [HAR 1.2 Request Object](http://www.softwareishard.com/blog/har-12-spec/#request), will be processed from HAR format into options overwriting matching values *(see the [HAR 1.2 section](#support-for-har-1.2) for details)*
- `callback` - alternatively pass the request's callback in the options object

@@ -891,52 +908,16 @@

### request.put
### request.METHOD()
Same as `request()`, but defaults to `method: "PUT"`.
These HTTP method convenience functions act just like `request()` but with a default method already set for you:
```js
request.put(url)
```
- *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.patch
### request.cookie()
Same as `request()`, but defaults to `method: "PATCH"`.
```js
request.patch(url)
```
### request.post
Same as `request()`, but defaults to `method: "POST"`.
```js
request.post(url)
```
### request.head
Same as `request()`, but defaults to `method: "HEAD"`.
```js
request.head(url)
```
### request.del / request.delete
Same as `request()`, but defaults to `method: "DELETE"`.
```js
request.del(url)
request.delete(url)
```
### request.get
Same as `request()` (for uniformity).
```js
request.get(url)
```
### request.cookie
Function that creates a new cookie.

@@ -1054,3 +1035,4 @@

}
).on('data', function(data) {
)
.on('data', function(data) {
// decompressed data as it is received

@@ -1057,0 +1039,0 @@ console.log('decoded chunk: ' + data)

'use strict'
var http = require('http')
, https = require('https')
, url = require('url')
, util = require('util')
, stream = require('stream')
, zlib = require('zlib')
, hawk = require('hawk')
, aws2 = require('aws-sign2')
, aws4 = require('aws4')
, httpSignature = require('http-signature')
, mime = require('mime-types')
, stringstream = require('stringstream')
, caseless = require('caseless')
, ForeverAgent = require('forever-agent')
, FormData = require('form-data')
, extend = require('extend')
, isstream = require('isstream')
, isTypedArray = require('is-typedarray').strict
, helpers = require('./lib/helpers')
, cookies = require('./lib/cookies')
, getProxyFromURI = require('./lib/getProxyFromURI')
, Querystring = require('./lib/querystring').Querystring
, Har = require('./lib/har').Har
, Auth = require('./lib/auth').Auth
, OAuth = require('./lib/oauth').OAuth
, Multipart = require('./lib/multipart').Multipart
, Redirect = require('./lib/redirect').Redirect
, Tunnel = require('./lib/tunnel').Tunnel
, now = require('performance-now')
, Buffer = require('safe-buffer').Buffer
var https = require('https')
var url = require('url')
var util = require('util')
var stream = require('stream')
var zlib = require('zlib')
var hawk = require('hawk')
var aws2 = require('aws-sign2')
var aws4 = require('aws4')
var httpSignature = require('http-signature')
var mime = require('mime-types')
var stringstream = require('stringstream')
var caseless = require('caseless')
var ForeverAgent = require('forever-agent')
var FormData = require('form-data')
var extend = require('extend')
var isstream = require('isstream')
var isTypedArray = require('is-typedarray').strict
var helpers = require('./lib/helpers')
var cookies = require('./lib/cookies')
var getProxyFromURI = require('./lib/getProxyFromURI')
var Querystring = require('./lib/querystring').Querystring
var Har = require('./lib/har').Har
var Auth = require('./lib/auth').Auth
var OAuth = require('./lib/oauth').OAuth
var Multipart = require('./lib/multipart').Multipart
var Redirect = require('./lib/redirect').Redirect
var Tunnel = require('./lib/tunnel').Tunnel
var now = require('performance-now')
var Buffer = require('safe-buffer').Buffer
var safeStringify = helpers.safeStringify
, isReadStream = helpers.isReadStream
, toBase64 = helpers.toBase64
, defer = helpers.defer
, copy = helpers.copy
, version = helpers.version
, globalCookieJar = cookies.jar()
var isReadStream = helpers.isReadStream
var toBase64 = helpers.toBase64
var defer = helpers.defer
var copy = helpers.copy
var version = helpers.version
var globalCookieJar = cookies.jar()
var globalPool = {}
function filterForNonReserved(reserved, options) {
function filterForNonReserved (reserved, options) {
// Filter out properties that are not reserved.

@@ -59,3 +58,3 @@ // Reserved values are passed in at call site.

function filterOutReservedFunctions(reserved, options) {
function filterOutReservedFunctions (reserved, options) {
// Filter out properties that are functions and are reserved.

@@ -73,7 +72,6 @@ // Reserved values are passed in at call site.

return object
}
// Return a simpler request object to allow serialization
function requestToJSON() {
function requestToJSON () {
var self = this

@@ -88,3 +86,3 @@ return {

// Return a simpler response object to allow serialization
function responseToJSON() {
function responseToJSON () {
var self = this

@@ -140,3 +138,3 @@ return {

Request.debug = process.env.NODE_DEBUG && /\brequest\b/.test(process.env.NODE_DEBUG)
function debug() {
function debug () {
if (Request.debug) {

@@ -265,3 +263,3 @@ console.error('REQUEST %s', util.format.apply(util, arguments))

if (!self.uri.pathname) {self.uri.pathname = '/'}
if (!self.uri.pathname) { self.uri.pathname = '/' }

@@ -308,4 +306,3 @@ if (!(self.uri.host || (self.uri.hostname && self.uri.port)) && !self.uri.isUnix) {

if (!self.uri.port) {
if (self.uri.protocol === 'http:') {self.uri.port = 80}
else if (self.uri.protocol === 'https:') {self.uri.port = 443}
if (self.uri.protocol === 'http:') { self.uri.port = 80 } else if (self.uri.protocol === 'https:') { self.uri.port = 443 }
}

@@ -397,3 +394,3 @@

if (self.uri.auth && !self.hasHeader('authorization')) {
var uriAuthPieces = self.uri.auth.split(':').map(function(item) {return self._qs.unescape(item)})
var uriAuthPieces = self.uri.auth.split(':').map(function (item) { return self._qs.unescape(item) })
self.auth(uriAuthPieces[0], uriAuthPieces.slice(1).join(':'), true)

@@ -403,3 +400,3 @@ }

if (!self.tunnel && self.proxy && self.proxy.auth && !self.hasHeader('proxy-authorization')) {
var proxyAuthPieces = self.proxy.auth.split(':').map(function(item) {return self._qs.unescape(item)})
var proxyAuthPieces = self.proxy.auth.split(':').map(function (item) { return self._qs.unescape(item) })
var authHeader = 'Basic ' + toBase64(proxyAuthPieces.join(':'))

@@ -436,7 +433,5 @@ self.setHeader('proxy-authorization', authHeader)

length = Buffer.byteLength(self.body)
}
else if (Array.isArray(self.body)) {
length = self.body.reduce(function (a, b) {return a + b.length}, 0)
}
else {
} else if (Array.isArray(self.body)) {
length = self.body.reduce(function (a, b) { return a + b.length }, 0)
} else {
length = self.body.length

@@ -463,4 +458,4 @@ }

var protocol = self.proxy && !self.tunnel ? self.proxy.protocol : self.uri.protocol
, defaultModules = {'http:':http, 'https:':https}
, httpModules = self.httpModules || {}
var defaultModules = {'http:': http, 'https:': https}
var httpModules = self.httpModules || {}

@@ -530,5 +525,5 @@ self.httpModule = httpModules[protocol] || defaultModules[protocol]

// self.on('pipe', function () {
// console.error('You have already piped to this stream. Pipeing twice is likely to break the request.')
// })
// self.on('pipe', function () {
// console.error('You have already piped to this stream. Pipeing twice is likely to break the request.')
// })
})

@@ -545,4 +540,3 @@

self._form.pipe(self)
}
else if (self._auth.hasAuth && self._auth.sentAuth) {
} else if (self._auth.hasAuth && self._auth.sentAuth) {
self._form.pipe(self)

@@ -598,3 +592,2 @@ }

})
}

@@ -794,6 +787,7 @@

self.req.on('error', self.onRequestError.bind(self))
self.req.on('drain', function() {
self.req.on('drain', function () {
self.emit('drain')
})
self.req.on('socket', function(socket) {
self.req.on('socket', function (socket) {
// `._connecting` was the old property which was made public in node v6.1.0

@@ -805,7 +799,7 @@ var isConnecting = socket._connecting || socket.connecting

if (isConnecting) {
var onLookupTiming = function() {
var onLookupTiming = function () {
self.timings.lookup = now() - self.startTimeNow
}
var onConnectTiming = function() {
var onConnectTiming = function () {
self.timings.connect = now() - self.startTimeNow

@@ -818,3 +812,3 @@ }

// clean up timing event listeners if needed on error
self.req.once('error', function() {
self.req.once('error', function () {
socket.removeListener('lookup', onLookupTiming)

@@ -826,3 +820,3 @@ socket.removeListener('connect', onConnectTiming)

var setReqTimeout = function() {
var setReqTimeout = function () {
// This timeout sets the amount of time to wait *between* bytes sent

@@ -849,3 +843,3 @@ // from the server once connected.

if (isConnecting) {
var onReqSockConnect = function() {
var onReqSockConnect = function () {
socket.removeListener('connect', onReqSockConnect)

@@ -859,3 +853,3 @@ clearTimeout(self.timeoutTimer)

self.req.on('error', function(err) {
self.req.on('error', function (err) { // eslint-disable-line handle-callback-err
socket.removeListener('connect', onReqSockConnect)

@@ -892,4 +886,4 @@ })

}
if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET'
&& self.agent.addRequestNoreuse) {
if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET' &&
self.agent.addRequestNoreuse) {
self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) }

@@ -915,3 +909,3 @@ self.start()

debug('onRequestResponse', self.uri.href, response.statusCode, response.headers)
response.on('end', function() {
response.on('end', function () {
if (self.timing) {

@@ -972,4 +966,4 @@ self.timings.end = now() - self.startTimeNow

if (self.httpModule === https &&
self.strictSSL && (!response.hasOwnProperty('socket') ||
!response.socket.authorized)) {
self.strictSSL && (!response.hasOwnProperty('socket') ||
!response.socket.authorized)) {
debug('strict ssl error', self.uri.href)

@@ -999,3 +993,3 @@ var sslErr = response.hasOwnProperty('socket') ? response.socket.authorizationError : self.uri.href + ' does not support SSL'

var addCookie = function (cookie) {
//set the cookie if it's domain in the href's domain.
// set the cookie if it's domain in the href's domain.
try {

@@ -1036,9 +1030,9 @@ targetCookieJar.setCookie(cookie, self.uri.href, {ignoreError: true})

return (
self.method === 'HEAD'
self.method === 'HEAD' ||
// Informational
|| (code >= 100 && code < 200)
(code >= 100 && code < 200) ||
// No Content
|| code === 204
code === 204 ||
// Not Modified
|| code === 304
code === 304
)

@@ -1057,4 +1051,4 @@ }

var zlibOptions = {
flush: zlib.Z_SYNC_FLUSH
, finishFlush: zlib.Z_SYNC_FLUSH
flush: zlib.Z_SYNC_FLUSH,
finishFlush: zlib.Z_SYNC_FLUSH
}

@@ -1121,9 +1115,7 @@

})
responseContent.on('close', function () {self.emit('close')})
responseContent.on('close', function () { self.emit('close') })
if (self.callback) {
self.readResponseBody(response)
}
//if no callback
else {
} else { // if no callback
self.on('end', function () {

@@ -1143,6 +1135,6 @@ if (self._aborted) {

var self = this
debug('reading response\'s body')
debug("reading response's body")
var buffers = []
, bufferLength = 0
, strings = []
var bufferLength = 0
var strings = []

@@ -1208,4 +1200,3 @@ self.on('data', function (chunk) {

self.req.abort()
}
else if (self.response) {
} else if (self.response) {
self.response.destroy()

@@ -1226,4 +1217,3 @@ }

dest.setHeader(ctname, response.headers[ctname])
}
else {
} else {
dest.headers[ctname] = response.headers[ctname]

@@ -1299,3 +1289,3 @@ }

self._form = new FormData()
self._form.on('error', function(err) {
self._form.on('error', function (err) {
err.message = 'form-data: ' + err.message

@@ -1375,4 +1365,4 @@ self.emit('error', err)

var unixParts = this.uri.path.split(':')
, host = unixParts[0]
, path = unixParts[1]
var host = unixParts[0]
var path = unixParts[1]
// Apply unix properties to request

@@ -1387,3 +1377,2 @@ this.socketPath = host

Request.prototype.auth = function (user, pass, sendImmediately, bearer) {

@@ -1404,3 +1393,3 @@ var self = this

if (opts.sign_version == 4 || opts.sign_version == '4') {
if (opts.sign_version === 4 || opts.sign_version === '4') {
// use aws4

@@ -1426,16 +1415,15 @@ var options = {

}
}
else {
} else {
// default: use aws-sign2
var date = new Date()
self.setHeader('date', date.toUTCString())
var auth =
{ key: opts.key
, secret: opts.secret
, verb: self.method.toUpperCase()
, date: date
, contentType: self.getHeader('content-type') || ''
, md5: self.getHeader('content-md5') || ''
, amazonHeaders: aws2.canonicalizeHeaders(self.headers)
}
var auth = {
key: opts.key,
secret: opts.secret,
verb: self.method.toUpperCase(),
date: date,
contentType: self.getHeader('content-type') || '',
md5: self.getHeader('content-md5') || '',
amazonHeaders: aws2.canonicalizeHeaders(self.headers)
}
var path = self.uri.path

@@ -1460,6 +1448,6 @@ if (opts.bucket && path) {

httpSignature.signRequest({
getHeader: function(header) {
getHeader: function (header) {
return self.getHeader(header, self.headers)
},
setHeader: function(header, value) {
setHeader: function (header, value) {
self.setHeader(header, value)

@@ -1501,3 +1489,3 @@ },

var urihref = self.uri.href
//fetch cookie in the Specified host
// fetch cookie in the Specified host
if (targetCookieJar) {

@@ -1508,3 +1496,3 @@ cookies = targetCookieJar.getCookieString(urihref)

//if need cookie and cookie is not empty
// if need cookie and cookie is not empty
if (cookies && cookies.length) {

@@ -1522,3 +1510,2 @@ if (self.originalCookieHeader) {

// Stream API

@@ -1546,3 +1533,3 @@ Request.prototype.pipe = function (dest, opts) {

var self = this
if (self._aborted) {return}
if (self._aborted) { return }

@@ -1558,3 +1545,3 @@ if (!self._started) {

var self = this
if (self._aborted) {return}
if (self._aborted) { return }

@@ -1561,0 +1548,0 @@ if (chunk) {

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc