Http Client Factory
This library is aimed at improving the development experience for REST-like calls in
NodeJS. It builds off the Node http
library. It's inspired by the
System.Net.Http.HttpClientFactory library in .NET.
Basic Usage
var HttpClientFactory = //Issues a GET request to http://www.tempuri.org/my/endpoint?some=value&search=textvar promise = HttpClientFactory promise
API
HttpClientFactory
.getClient(AgentOptions)
- Returns
HttpClient
AgentOptions
is fromhttp
library- If
AgentOptions
is null, default settings are used (recommended)
HttpClient
.addHeader(headerKey, headerValue)
- Adds a header to the request with the given key and value
.setAuthorization(scheme, parameter)
- Sets the Authorization header to
scheme parameter
- Returns
HttpClient
.setBasicAuth(username, password)
- Sets the Authorization header to use basic authentication with the given credentials
- Returns
HttpClient
.addHandler(HttpClientHandler)
- Adds an HttpClientHandler to run on requests and responses
- Request handlers are run in the order they're added. The first handler added will run first
- Response handlers are run in the reverse order. The last handler added will run first
- Returns
HttpClient
.get(url, RequestBody)
- Returns
Promise
.post(url, RequestBody)
- Returns
Promise
.put(url, RequestBody)
- Returns
Promise
.delete(url, RequestBody)
- Returns
Promise
.send(HttpRequest, RequestBody)
- Sends a raw request
- Returns
Promise
HttpClientHandler
onRequest: function (HttpRequest, body)
- Reads or modifies request and/or body as needed
- Leave undefined if not needed
onResponse: function (HttpResponse)
- Reads or modifies response if needed
- Leave undefined if not needed
RequestBody
- Normal JSON object
- For
.get()
,.delete()
,.head()
, and.options()
requests, this will be converted into query string parameters - For
.put()
,.post()
, and.patch()
requests, this will be sent as JSON content
Reading the Response
The response is a typical HTTP response as defined by the http
library,
with the addition of a body
property which contains the response content
(in string form).
Handlers
Setting authorization headers
var handler = { reqheadersauthorization = "sampleAuthScheme authValue"; } //Issues a POST request to the URL //with the authorization header set to "sampleAuthScheme authValue"//and a JSON payload of { "postdata": "goes here" }HttpClientFactory
As of v0.2.0, this can be accomplished by calling
client.setAuthorization("sampleAuthScheme", "authValue")
Logging request/response data
var traceLogHandler = { var logger = logger } { var logger = logger } //Logs both request and response data to myTraceLoggerHttpClientFactory
Promises
httpClientFactory
uses the bluebird library for promises