An H2CClient is a Dispatcher that speaks HTTP/2 in cleartext (h2c) over a
single TCP connection to an http: origin, without the protocol upgrade or prior
knowledge negotiation that a regular Client performs. It is a thin
specialization of Client that forces allowH2 and useH2c on and aliases
pipelining to maxConcurrentStreams, so multiple requests are multiplexed as
HTTP/2 streams rather than pipelined HTTP/1.x requests.
Use an H2CClient when the server is known to accept cleartext HTTP/2 directly,
for example a service behind a trusted proxy or in a test environment. Only the
http: protocol is supported; passing any other protocol throws
InvalidArgumentError.
import { H2CClient } from 'undici'
const client = new H2CClient('http://localhost:3000')
const { statusCode, body } = await client.request({ path: '/', method: 'GET' })
console.log(statusCode)
console.log(await body.text())class H2CClient extends ClientH2CClient inherits the full instance API of Client (and therefore of
Dispatcher). The sections below cover the surface that is meaningful for an
h2c client; refer to Dispatcher for the complete semantics of each method
and event.
new H2CClient(url, options?): voidhttp:
protocol is supported.<H2CClientOptions><number>SETTINGS
frame. Must be a positive integer.
Default:
100
.<number>H2CClient
this is aliased to
maxConcurrentStreams
and may not exceed it. Must be a positive integer.
Default:
100
.<number>--max-http-header-size
or
16384
(16 KiB).<number>300e3
.<number>0
to disable it entirely.
Default:
10e3
.<number>0
to disable
it entirely.
Default:
300e3
.<number>4e3
.<number>keepAliveTimeout
, in
milliseconds, when overridden by
keep-alive
hints from the server.
Default:
600e3
.<number>keepAliveTimeout
, to account for
timing inaccuracies such as transport latency.
Default:
1e3
.<string>null
.<boolean>true
, an error is thrown when the
request
content-length
header does not match the length of the request
body.
Default:
true
.<number>0
to disable TLS session caching.
Default:
100
.<Object>
|
<Function>buildConnector
, or
a custom connector function. The
allowH2
option may not be set here.
Default:
null
.<number>0
to disable this limit.
Default:
null
.<string><number>-1
to disable.
Default:
-1
.<boolean><number>autoSelectFamily
is enabled.Creates a new H2CClient for the given origin. The client does not connect until
a request is queued; call h2cClient.connect()
to connect eagerly.
import { H2CClient } from 'undici'
const client = new H2CClient('http://localhost:3000')h2cClient.close(callback?): Promise | undefined<Function><Promise>
|
<undefined>Promise
that resolves once the client is
closed, when
callback
is not provided.Closes the client and gracefully waits for enqueued requests to complete before
resolving. See [dispatcher.close([callback])][].
h2cClient.destroy(error?, callback?): Promise | undefined<Error>null
.<Function><Promise>
|
<undefined>Promise
that resolves once the client is
destroyed, when
callback
is not provided.Destroys the client abruptly, aborting any pending requests. Waits until the
socket is closed before invoking callback (or resolving the returned Promise).
See [dispatcher.destroy([error[, callback]])][].
h2cClient.connect(options, callback?): Promise | undefined<Object><string><Object>null
.<AbortSignal>
|
<EventEmitter>
|
<null>null
.<any><Function>(err, data)
once the connection
is established. If omitted, a
Promise
is returned instead.<Promise>
|
<undefined>Promise
resolving to the connect data, when
callback
is not provided.Starts an HTTP CONNECT request. See [dispatcher.connect(options[, callback])][].
h2cClient.dispatch(options, handlers): boolean<boolean>false
if the dispatcher is busy and the caller should wait
for the
'drain'
event before dispatching again.The lowest-level request API. All other request methods are implemented on top of
it. See [dispatcher.dispatch(options, handler)][].
h2cClient.pipeline(options, handler): Duplex<Object><Function><Readable>
body.<Duplex>Sends a request and returns a duplex stream, suitable for piping. See
[dispatcher.pipeline(options, handler)][].
h2cClient.request(options, callback?): Promise | undefined<Object><Function>(err, data)
once the response
is received. If omitted, a
Promise
is returned instead.<Promise>
|
<undefined>Promise
resolving to the response data, when
callback
is not provided.Performs an HTTP request. See [dispatcher.request(options[, callback])][].
h2cClient.stream(options, factory, callback?): Promise | undefined<Object><Function><Writable>
to which the response
body is written.<Function>Promise
is returned instead.<Promise>
|
<undefined>Promise
that resolves once the request
completes, when
callback
is not provided.Sends a request and writes the response body to the stream returned by factory.
See [dispatcher.stream(options, factory[, callback])][].
h2cClient.upgrade(options, callback?): Promise | undefined<Object><Function>(err, data)
once the upgrade
completes. If omitted, a
Promise
is returned instead.<Promise>
|
<undefined>Promise
resolving to the upgrade data, when
callback
is not provided.Upgrades a connection to a different protocol. See
[dispatcher.upgrade(options[, callback])][].
<boolean>true after h2cClient.close() has been called.
<boolean>true after h2cClient.destroy() has been
called, or after h2cClient.close() has been called
and the client shutdown has completed.
<number>Gets and sets the pipelining factor, i.e. the number of requests multiplexed over the connection.
<URL>Emitted when the socket has been created and connected. The client connects once
client.size > 0. See Dispatcher Event: 'connect'.
import { createServer } from 'node:http2'
import { once } from 'node:events'
import { H2CClient } from 'undici'
const server = createServer((request, response) => {
response.end('Hello, World!')
}).listen()
await once(server, 'listening')
const client = new H2CClient(`http://localhost:${server.address().port}`)
client.on('connect', (origin) => {
console.log(`Connected to ${origin}`)
})
const { body } = await client.request({ path: '/', method: 'GET' })
console.log(await body.text())
client.close()
server.close()Emitted when the socket has disconnected. The error argument is the error that
caused the socket to disconnect. The client reconnects if (or once)
client.size > 0. See Dispatcher Event: 'disconnect'.
import { createServer } from 'node:http2'
import { once } from 'node:events'
import { H2CClient } from 'undici'
const server = createServer((request, response) => {
response.destroy()
}).listen()
await once(server, 'listening')
const client = new H2CClient(`http://localhost:${server.address().port}`)
client.on('disconnect', (origin) => {
console.log(`Disconnected from ${origin}`)
})
try {
await client.request({ path: '/', method: 'GET' })
} catch (error) {
console.error(error.message)
} finally {
client.close()
server.close()
}<URL>Emitted when the client is no longer busy and can accept more requests. See
Dispatcher Event: 'drain'.
<Error>Emitted for user errors, such as an error thrown from an onResponseError
handler.
[dispatcher.close([callback])]: Dispatcher.md#dispatcherclosecallback
[dispatcher.connect(options[, callback])]: Dispatcher.md#dispatcherconnectoptions-callback
[dispatcher.destroy([error[, callback]])]: Dispatcher.md#dispatcherdestroyerror-callback
[dispatcher.dispatch(options, handler)]: Dispatcher.md#dispatcherdispatchoptions-handler
[dispatcher.pipeline(options, handler)]: Dispatcher.md#dispatcherpipelineoptions-handler
[dispatcher.request(options[, callback])]: Dispatcher.md#dispatcherrequestoptions-callback
[dispatcher.stream(options, factory[, callback])]: Dispatcher.md#dispatcherstreamoptions-factory-callback
[dispatcher.upgrade(options[, callback])]: Dispatcher.md#dispatcherupgradeoptions-callback