Streaming

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

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:

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:

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

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.

sendImmediately defaults to true, which causes a basic or bearer
authentication header to be sent. If sendImmediately is false, then
request will retry with a proper authentication header after receiving a
401 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 the
user:password before the host with an @ sign:

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 a
String. 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.

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.

By default, when proxying http traffic, request will simply make a
standard proxied http request. This is done by making the url
section of the initial line of the request a fully qualified url to
the endpoint.

Because a pure "http over http" tunnel offers no additional security
or other features, it is generally simpler to go with a
straightforward HTTP proxy in this case. However, if you would like
to force a tunneling proxy, you may set the tunnel option to true.

You can also make a standard proxied http request by explicitly setting
tunnel : false, but note that this will allow the proxy to see the traffic
to/from the destination server.

If you are using a tunneling proxy, you may set the
proxyHeaderWhiteList to share certain headers with the proxy.

You can also set the proxyHeaderExclusiveList to share certain
headers only with the proxy and not with destination host.

Note that, when using a tunneling proxy, the proxy-authorization
header and any headers from custom proxyHeaderExclusiveList are
never sent to the endpoint server, but only to the proxy server.

Controlling proxy behaviour using environment variables

The following environment variables are respected by request:

HTTP_PROXY / http_proxy

HTTPS_PROXY / https_proxy

NO_PROXY / no_proxy

When HTTP_PROXY / http_proxy are set, they will be used to proxy non-SSL requests that do not have an explicit proxy configuration option present. Similarly, HTTPS_PROXY / https_proxy will be respected for SSL requests that do not have an explicit proxy configuration option. It is valid to define a proxy in one of the environment variables, but then override it for a specific request, using the proxy configuration option. Furthermore, the proxy configuration option can be explicitly set to false / null to opt out of proxying altogether for that request.

request is also aware of the NO_PROXY/no_proxy environment variables. These variables provide a granular way to opt out of proxying, on a per-host basis. It should contain a comma separated list of hosts to opt out of proxying. It is also possible to opt of proxying when a particular destination port is used. Finally, the variable may be set to * to opt out of the implicit proxy configuration of the other environment variables.

TLS/SSL Protocol

TLS/SSL Protocol options, such as cert, key and passphrase, can be
set directly in options object, in the agentOptions property of the options object, or even in https.globalAgent.options. Keep in mind that, although agentOptions allows for a slightly wider range of configurations, the recommended way is via options object directly, as using agentOptions or https.globalAgent.options would not be applied in the same way in proxied environments (as data travels through a TLS connection instead of an http/https agent).

It is possible to accept other certificates than those signed by generally allowed Certificate Authorities (CAs).
This can be useful, for example, when using self-signed certificates.
To require a different root certificate, you can specify the signing CA by adding the contents of the CA's certificate file to the agentOptions.
The certificate the domain presents must be signed by the root certificate specified:

The ca value can be an array of certificates, in the event you have a private or internal corporate public-key infrastructure hierarchy. For example, if you want to connect to https://api.some-server.com which presents a key chain consisting of:

Support for HAR 1.2

The options.har property will override the values: url, method, qs, headers, form, formData, body, json, as well as construct multipart data and read files from disk when request.postData.params[].fileName is present without a matching value.

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

request(options, callback)

baseUrl - fully qualified uri string used as the base url. Most useful with request.defaults, for example when you want to do many requests to the same domain. If baseUrl is https://example.com/api/, then requesting /end/point?test=true will fetch https://example.com/api/end/point?test=true. When baseUrl is given, uri must also be a string.

qsStringifyOptions - object containing options to pass to the qs.stringify method. Alternatively pass options to the querystring.stringify 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
querystrings, otherwise use qs (default: false). Set this option to
true if you need arrays to be serialized as foo=bar&foo=baz instead of the
default foo[0]=bar&foo[1]=baz.

body - entity body for PATCH, POST and PUT requests. Must be a Buffer, String or ReadStream. If json is true, then body must be a JSON-serializable object.

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
Forms section above.

multipart - array of objects which contain their own headers and body
attributes. Sends a multipart/related request. See Forms section
above.

Alternatively you can pass in an object {chunked: false, data: []} where
chunked is used to specify whether the request is sent in
chunked transfer encoding
In non-chunked requests, data items with body streams are not allowed.

preambleCRLF - append a newline/CRLF before the boundary of your multipart/form-data request.

postambleCRLF - append a newline/CRLF at the end of the boundary of your multipart/form-data request.

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. If you are using SigV4, you can also include a service property that specifies the service name. Note: you need to npm install aws4 first.

followRedirect - follow HTTP 3xx responses as redirects (default: true). This property can also be implemented as function which gets response object as a single argument and should return true if redirects should continue or false otherwise.

followOriginalHttpMethod - by default we redirect to HTTP method GET. you can enable this property to redirect to the original HTTP method (default: false)

maxRedirects - the maximum number of redirects to follow (default: 10)

removeRefererHeader - removes the referer header when a redirect happens (default: false). Note: if true, referer header set in the initial request is preserved during redirect chain.

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

forever - set to true to use the forever-agentNote: 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.

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}).

Note that if you are sending multiple requests in a loop and creating
multiple new pool objects, maxSockets will not work as intended. To
work around this, either use request.defaults
with your pool options or create the pool object with the maxSockets
property outside of the loop.

timeout - integer containing number of milliseconds, controls two timeouts

Time 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 (the
default in Linux can be anywhere from 20-120 seconds).

Sets the socket to timeout after timeout milliseconds of inactivity on the socket.

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.

Convenience methods

There are also shorthand methods for different HTTP METHODs and some other conveniences.

request.defaults(options)

This method returns a wrapper around the normal request API that defaults
to whatever options you pass to it.

Note:request.defaults()does not modify the global request API;
instead, it returns a wrapper that has your default settings applied to it.

Note: You can call .defaults() on the wrapper that is returned from
request.defaults to add/override defaults that were previously defaulted.

For example:

//requests using baseRequest() will set the 'x-token' headerconstbaseRequest=request.defaults({
headers: {'x-token':'my-token'}
})
//requests using specialRequest() will include the 'x-token' header set in//baseRequest and will also include the 'special' headerconstspecialRequest=baseRequest.defaults({
headers: {special:'special value'}
})

request.METHOD()

These HTTP method convenience functions act just like request() but with a default method already set for you:

Timeouts

Most requests to external servers should have a timeout attached, in case the
server is not responding in a timely manner. Without a timeout, your code may
have a socket open/consume resources for minutes or more.

There are two main types of timeouts: connection timeouts and read
timeouts. A connect timeout occurs if the timeout is hit while your client is
attempting to establish a connection to a remote machine (corresponding to the
connect() call on the socket). A read timeout occurs any time the
server is too slow to send back a part of the response.

These two situations have widely different implications for what went wrong
with the request, so it's useful to be able to distinguish them. You can detect
timeout errors by checking err.code for an 'ETIMEDOUT' value. Further, you
can detect whether the timeout was a connection timeout by checking if the
err.connect property is set to true.

For backwards-compatibility, response compression is not supported by default.
To accept gzip-compressed responses, set the gzip option to true. Note
that the body data passed through request is automatically decompressed
while the response object is unmodified and will contain compressed data if
the server sent a compressed response.