📡 A tiny Node HTTP(S) request wrapper, for JSON requests and responses, with timeout support and status code validation.
const request = ;;
request(options[, data], callback): Creates a new HTTPS request, passing the
optionsto Node http.request, except for these properties:
protocol: The protocol to use. Must be either
"https:". Defaults to
timeout: The number of milliseconds after which the request should time out, causing en
expect: The expected status code(s). This can be a number or an array of numbers.
callbackis invoked with
(null, res)once the header was retrieved to allow to stream the response.
timeoutoption is specified, a timer is installed which will abort the request and invoke the callback with an error.
expectoption is specified, it validates the response HTTP status code. If it's a number the status code has to equal that number. If an array is given, any number in the array is accepted. If the option is not given, the request will fail for non
streamoption is specified, the response is returned immediately after the status code was checked. No further response processing is done by this library. It is the callers responsibility to consume the response.
datais given, it is stringified and passed as the request body and the request is sent. The
Content-Typeheader is set to
application/json, unless this header was already provided. The
Content-Lengthis set to the request body length.
datais set to
null, the request is sent without a body.
datais omitted, the request object is returned and it's the callers responsibility to invoke
req.end()to complete the request.
The callback is invoked with
(err, data, response).
err: An error object or
null. The error will have a
codeproperty with these possible string values:
E_TIMEOUT: The request timed out.
E_EXPECT: The response status code does not match the expectation. The
statusCodeproperty on the error object is set to the response status code.
E_JSON: Could not parse the response body as JSON. In this case
datais the raw body.
E_ERROR: If an
errorevent was thrown.
data: The parsed response data, or if it could not be parsed the raw body.
response: The response object.