Node.js v8.x 中文文档
目录
- HTTP2
- Core API
- Server-side example
- Client-side example
- Class: Http2Session
- Http2Session and Sockets
- Event: 'close'
- Event: 'connect'
- Event: 'error'
- Event: 'frameError'
- Event: 'goaway'
- Event: 'localSettings'
- Event: 'remoteSettings'
- Event: 'stream'
- Event: 'socketError'
- Event: 'timeout'
- http2session.destroy()
- http2session.destroyed
- http2session.localSettings
- http2session.pendingSettingsAck
- http2session.ping([payload, ]callback)
- http2session.remoteSettings
- http2session.request(headers[, options])
- http2session.setTimeout(msecs, callback)
- http2session.shutdown(options[, callback])
- http2session.socket
- http2session.state
- http2session.settings(settings)
- http2session.type
- Class: Http2Stream
- Http2Stream Lifecycle
- Event: 'aborted'
- Event: 'close'
- Event: 'error'
- Event: 'frameError'
- Event: 'timeout'
- Event: 'trailers'
- http2stream.aborted
- http2stream.destroyed
- http2stream.priority(options)
- http2stream.rstCode
- http2stream.rstStream(code)
- http2stream.rstWithNoError()
- http2stream.rstWithProtocolError()
- http2stream.rstWithCancel()
- http2stream.rstWithRefuse()
- http2stream.rstWithInternalError()
- http2stream.session
- http2stream.setTimeout(msecs, callback)
- http2stream.state
- Class: ClientHttp2Stream
- Class: ServerHttp2Stream
- Class: Http2Server
- Class: Http2SecureServer
- http2.createServer(options[, onRequestHandler])
- http2.createSecureServer(options[, onRequestHandler])
- http2.connect(authority[, options][, listener])
- http2.constants
- http2.getDefaultSettings()
- http2.getPackedSettings(settings)
- http2.getUnpackedSettings(buf)
- Headers Object
- Settings Object
- Using
options.selectPadding
- Error Handling
- Invalid character handling in header names and values
- Push streams on the client
- Supporting the CONNECT method
- Compatibility API
- ALPN negotiation
- Class: http2.Http2ServerRequest
- Class: http2.Http2ServerResponse
- Event: 'close'
- Event: 'finish'
- response.addTrailers(headers)
- response.connection
- response.end([data][, encoding][, callback])
- response.finished
- response.getHeader(name)
- response.getHeaderNames()
- response.getHeaders()
- response.hasHeader(name)
- response.headersSent
- response.removeHeader(name)
- response.sendDate
- response.setHeader(name, value)
- response.setTimeout(msecs[, callback])
- response.socket
- response.statusCode
- response.statusMessage
- response.stream
- response.write(chunk[, encoding][, callback])
- response.writeContinue()
- response.writeHead(statusCode[, statusMessage][, headers])
- response.createPushResponse(headers, callback)
- Core API
HTTP2#
The http2
module provides an implementation of the HTTP/2 protocol. Itcan be accessed using:
const http2 = require('http2');
Core API#
The Core API provides a low-level interface designed specifically aroundsupport for HTTP/2 protocol features. It is specifically not designed forcompatibility with the existing HTTP/1 module API. However,the Compatibility API is.
The http2
Core API is much more symmetric between client and server than thehttp
API. For instance, most events, like error
and socketError
, can beemitted either by client-side code or server-side code.
Server-side example#
The following illustrates a simple, plain-text HTTP/2 server using theCore API:
const http2 = require('http2');const fs = require('fs');const server = http2.createSecureServer({ key: fs.readFileSync('localhost-privkey.pem'), cert: fs.readFileSync('localhost-cert.pem')});server.on('error', (err) => console.error(err));server.on('socketError', (err) => console.error(err));server.on('stream', (stream, headers) => { // stream is a Duplex stream.respond({ 'content-type': 'text/html', ':status': 200 }); stream.end('Hello World
');});server.listen(8443);
To generate the certificate and key for this example, run:
openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \ -keyout localhost-privkey.pem -out localhost-cert.pem
Client-side example#
The following illustrates an HTTP/2 client:
const http2 = require('http2');const fs = require('fs');const client = http2.connect('https://localhost:8443', { ca: fs.readFileSync('localhost-cert.pem')});client.on('socketError', (err) => console.error(err));client.on('error', (err) => console.error(err));const req = client.request({ ':path': '/' });req.on('response', (headers, flags) => { for (const name in headers) { console.log(`${name}: ${headers[name]}`); }});req.setEncoding('utf8');let data = '';req.on('data', (chunk) => { data += chunk; });req.on('end', () => { console.log(`\n${data}`); client.destroy();});req.end();
Class: Http2Session#
Instances of the http2.Http2Session
class represent an active communicationssession between an HTTP/2 client and server. Instances of this class are notintended to be constructed directly by user code.
Each Http2Session
instance will exhibit slightly different behaviorsdepending on whether it is operating as a server or a client. Thehttp2session.type
property can be used to determine the mode in which anHttp2Session
is operating. On the server side, user code should rarelyhave occasion to work with the Http2Session
object directly, with mostactions typically taken through interactions with either the Http2Server
orHttp2Stream
objects.
Http2Session and Sockets#
Every Http2Session
instance is associated with exactly one net.Socket
ortls.TLSSocket
when it is created. When either the Socket
or theHttp2Session
are destroyed, both will be destroyed.
Because the of the specific serialization and processing requirements imposedby the HTTP/2 protocol, it is not recommended for user code to read data fromor write data to a Socket
instance bound to a Http2Session
. Doing so canput the HTTP/2 session into an indeterminate state causing the session andthe socket to become unusable.
Once a Socket
has been bound to an Http2Session
, user code should relysolely on the API of the Http2Session
.
Event: 'close'#
The 'close'
event is emitted once the Http2Session
has been terminated.
Event: 'connect'#
The 'connect'
event is emitted once the Http2Session
has been successfullyconnected to the remote peer and communication may begin.
Note: User code will typically not listen for this event directly.
Event: 'error'#
The 'error'
event is emitted when an error occurs during the processing ofan Http2Session
.
Event: 'frameError'#
The 'frameError'
event is emitted when an error occurs while attempting tosend a frame on the session. If the frame that could not be sent is associatedwith a specific Http2Stream
, an attempt to emit 'frameError'
event on theHttp2Stream
is made.
When invoked, the handler function will receive three arguments:
- An integer identifying the frame type.
- An integer identifying the error code.
- An integer identifying the stream (or 0 if the frame is not associated witha stream).
If the 'frameError'
event is associated with a stream, the stream will beclosed and destroyed immediately following the 'frameError'
event. If theevent is not associated with a stream, the Http2Session
will be shutdownimmediately following the 'frameError'
event.
Event: 'goaway'#
The 'goaway'
event is emitted when a GOAWAY frame is received. When invoked,the handler function will receive three arguments:
errorCode
The HTTP/2 error code specified in the GOAWAY frame. lastStreamID
The ID of the last stream the remote peer successfullyprocessed (or 0
if no ID is specified).opaqueData
If additional opaque data was included in the GOAWAYframe, a Buffer
instance will be passed containing that data.
Note: The Http2Session
instance will be shutdown automatically when the'goaway'
event is emitted.
Event: 'localSettings'#
The 'localSettings'
event is emitted when an acknowledgement SETTINGS framehas been received. When invoked, the handler function will receive a copy ofthe local settings.
Note: When using http2session.settings()
to submit new settings, themodified settings do not take effect until the 'localSettings'
event isemitted.
session.settings({ enablePush: false });session.on('localSettings', (settings) => { /** use the new settings **/});
Event: 'remoteSettings'#
The 'remoteSettings'
event is emitted when a new SETTINGS frame is receivedfrom the connected peer. When invoked, the handler function will receive a copyof the remote settings.
session.on('remoteSettings', (settings) => { /** use the new settings **/});
Event: 'stream'#
The 'stream'
event is emitted when a new Http2Stream
is created. Wheninvoked, the handler function will receive a reference to the Http2Stream
object, a Headers Object, and numeric flags associated with the creationof the stream.
const http2 = require('http2');const { HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_STATUS, HTTP2_HEADER_CONTENT_TYPE} = http2.constants;session.on('stream', (stream, headers, flags) => { const method = headers[HTTP2_HEADER_METHOD]; const path = headers[HTTP2_HEADER_PATH]; // ... stream.respond({ [HTTP2_HEADER_STATUS]: 200, [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain' }); stream.write('hello '); stream.end('world');});
On the server side, user code will typically not listen for this event directly,and would instead register a handler for the 'stream'
event emitted by thenet.Server
or tls.Server
instances returned by http2.createServer()
andhttp2.createSecureServer()
, respectively, as in the example below:
const http2 = require('http2');// Create a plain-text HTTP/2 serverconst server = http2.createServer();server.on('stream', (stream, headers) => { stream.respond({ 'content-type': 'text/html', ':status': 200 }); stream.end('Hello World
');});server.listen(80);
Event: 'socketError'#
The 'socketError'
event is emitted when an 'error'
is emitted on theSocket
instance bound to the Http2Session
. If this event is not handled,the 'error'
event will be re-emitted on the Socket
.
For ServerHttp2Session
instances, a 'socketError'
event listener is alwaysregistered that will, by default, forward the event on to the owningHttp2Server
instance if no additional handlers are registered.
Event: 'timeout'#
After the http2session.setTimeout()
method is used to set the timeout periodfor this Http2Session
, the 'timeout'
event is emitted if there is noactivity on the Http2Session
after the configured number of milliseconds.
session.setTimeout(2000);session.on('timeout', () => { /** .. **/ });
http2session.destroy()#
Immediately terminates the Http2Session
and the associated net.Socket
ortls.TLSSocket
.
http2session.destroyed#
Will be true
if this Http2Session
instance has been destroyed and must nolonger be used, otherwise false
.
http2session.localSettings#
- Value: <Settings Object>
A prototype-less object describing the current local settings of thisHttp2Session
. The local settings are local to this Http2Session
instance.
http2session.pendingSettingsAck#
Indicates whether or not the Http2Session
is currently waiting for anacknowledgement for a sent SETTINGS frame. Will be true
after calling thehttp2session.settings()
method. Will be false
once all sent SETTINGSframes have been acknowledged.
http2session.ping([payload, ]callback)#
Sends a PING
frame to the connected HTTP/2 peer. A callback
function mustbe provided. The method will return true
if the PING
was sent, false
otherwise.
The maximum number of outstanding (unacknowledged) pings is determined by themaxOutstandingPings
configuration option. The default maximum is 10.
If provided, the payload
must be a Buffer
, TypedArray
, or DataView
containing 8 bytes of data that will be transmitted with the PING
andreturned with the ping acknowledgement.
The callback will be invoked with three arguments: an error argument that willbe null
if the PING
was successfully acknowledged, a duration
argumentthat reports the number of milliseconds elapsed since the ping was sent and theacknowledgement was received, and a Buffer
containing the 8-byte PING
payload.
session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => { if (!err) { console.log(`Ping acknowledged in ${duration} milliseconds`); console.log(`With payload '${payload.toString()}`); }});
If the payload
argument is not specified, the default payload will be the64-bit timestamp (little endian) marking the start of the PING
duration.
http2session.remoteSettings#
- Value: <Settings Object>
A prototype-less object describing the current remote settings of thisHttp2Session
. The remote settings are set by the connected HTTP/2 peer.
http2session.request(headers[, options])#
headers
<Headers Object>endStream
true
if theHttp2Stream
writable side shouldbe closed initially, such as when sending aGET
request that should notexpect a payload body.exclusive
When true
andparent
identifies a parent Stream,the created stream is made the sole direct dependency of the parent, withall other existing dependents made a dependent of the newly created stream.Default:false
parent
Specifies the numeric identifier of a stream the newlycreated stream is dependent on. weight
Specifies the relative dependency of a stream in relationto other streams with the same parent
. The value is a number between1
and256
(inclusive).getTrailers
Callback function invoked to collect trailerheaders.
Returns:
For HTTP/2 Client Http2Session
instances only, the http2session.request()
creates and returns an Http2Stream
instance that can be used to send anHTTP/2 request to the connected server.
This method is only available if http2session.type
is equal tohttp2.constants.NGHTTP2_SESSION_CLIENT
.
const http2 = require('http2');const clientSession = http2.connect('https://localhost:1234');const { HTTP2_HEADER_PATH, HTTP2_HEADER_STATUS} = http2.constants;const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' });req.on('response', (headers) => { console.log(headers[HTTP2_HEADER_STATUS]); req.on('data', (chunk) => { /** .. **/ }); req.on('end', () => { /** .. **/ });});
When set, the options.getTrailers()
function is called immediately afterqueuing the last chunk of payload data to be sent. The callback is passed asingle object (with a null
prototype) that the listener may used to specifythe trailing header fields to send to the peer.
Note: The HTTP/1 specification forbids trailers from containing HTTP/2"pseudo-header" fields (e.g. ':method'
, ':path'
, etc). An 'error'
eventwill be emitted if the getTrailers
callback attempts to set such headerfields.
http2session.setTimeout(msecs, callback)#
Used to set a callback function that is called when there is no activity onthe Http2Session
after msecs
milliseconds. The given callback
isregistered as a listener on the 'timeout'
event.
http2session.shutdown(options[, callback])#
options
graceful
true
to attempt a polite shutdown of theHttp2Session
.errorCode
The HTTP/2 error code to return. Note that this isnot the same thing as an HTTP Response Status Code. Default: 0x00
(No Error).lastStreamID
The Stream ID of the last successfully processed Http2Stream
on thisHttp2Session
.opaqueData
| A Buffer
orUint8Array
instancecontaining arbitrary additional data to send to the peer upon disconnection.This is used, typically, to provide additional data for debugging failures,if necessary.
callback
A callback that is invoked after the session shutdownhas been completed. - Returns:
Attempts to shutdown this Http2Session
using HTTP/2 defined procedures.If specified, the given callback
function will be invoked once the shutdownprocess has completed.
Note that calling http2session.shutdown()
does not destroy the session ortear down the Socket
connection. It merely prompts both sessions to beginpreparing to cease activity.
During a "graceful" shutdown, the session will first send a GOAWAY
frame tothe connected peer identifying the last processed stream as 232-1.Then, on the next tick of the event loop, a second GOAWAY
frame identifyingthe most recently processed stream identifier is sent. This process allows theremote peer to begin preparing for the connection to be terminated.
session.shutdown({ graceful: true, opaqueData: Buffer.from('add some debugging data here')}, () => session.destroy());
http2session.socket#
Returns a Proxy object that acts as a net.Socket
(or tls.TLSSocket
) butlimits available methods to ones safe to use with HTTP/2.
destroy
, emit
, end
, pause
, read
, resume
, and write
will throwan error with code ERR_HTTP2_NO_SOCKET_MANIPULATION
. SeeHttp2Session and Sockets for more information.
setTimeout
method will be called on this Http2Session
.
All other interactions will be routed directly to the socket.
http2session.state#
Provides miscellaneous information about the current state of theHttp2Session
.
- Value:
effectiveLocalWindowSize
The current local (receive)flow control window size for the Http2Session
.effectiveRecvDataLength
The current number of bytesthat have been received since the last flow control WINDOW_UPDATE
.nextStreamID
The numeric identifier to be used thenext time a new Http2Stream
is created by thisHttp2Session
.localWindowSize
The number of bytes that the remote peer cansend without receiving a WINDOW_UPDATE
.lastProcStreamID
The numeric id of the Http2Stream
for which aHEADERS
orDATA
frame was most recently received.remoteWindowSize
The number of bytes that this Http2Session
may send without receiving aWINDOW_UPDATE
.outboundQueueSize
The number of frames currently within theoutbound queue for this Http2Session
.deflateDynamicTableSize
The current size in bytes of theoutbound header compression state table. inflateDynamicTableSize
The current size in bytes of theinbound header compression state table.
An object describing the current status of this Http2Session
.
http2session.settings(settings)#
settings
<Settings Object>- Returns
Updates the current local settings for this Http2Session
and sends a newSETTINGS
frame to the connected HTTP/2 peer.
Once called, the http2session.pendingSettingsAck
property will be true
while the session is waiting for the remote peer to acknowledge the newsettings.
Note: The new settings will not become effective until the SETTINGSacknowledgement is received and the 'localSettings'
event is emitted. Itis possible to send multiple SETTINGS frames while acknowledgement is stillpending.
http2session.type#
The http2session.type
will be equal tohttp2.constants.NGHTTP2_SESSION_SERVER
if this Http2Session
instance is aserver, and http2.constants.NGHTTP2_SESSION_CLIENT
if the instance is aclient.
Class: Http2Stream#
- Extends:
Each instance of the Http2Stream
class represents a bidirectional HTTP/2communications stream over an Http2Session
instance. Any single Http2Session
may have up to 231-1 Http2Stream
instances over its lifetime.
User code will not construct Http2Stream
instances directly. Rather, theseare created, managed, and provided to user code through the Http2Session
instance. On the server, Http2Stream
instances are created either in responseto an incoming HTTP request (and handed off to user code via the 'stream'
event), or in response to a call to the http2stream.pushStream()
method.On the client, Http2Stream
instances are created and returned when either thehttp2session.request()
method is called, or in response to an incoming'push'
event.
Note: The Http2Stream
class is a base for the ServerHttp2Stream
andClientHttp2Stream
classes, each of which are used specifically by eitherthe Server or Client side, respectively.
All Http2Stream
instances are Duplex
streams. The Writable
side of theDuplex
is used to send data to the connected peer, while the Readable
sideis used to receive data sent by the connected peer.
Http2Stream Lifecycle#
Creation#
On the server side, instances of ServerHttp2Stream
are created eitherwhen:
- A new HTTP/2
HEADERS
frame with a previously unused stream ID is received; - The
http2stream.pushStream()
method is called.
On the client side, instances of ClientHttp2Stream
are created when thehttp2session.request()
method is called.
Note: On the client, the Http2Stream
instance returned byhttp2session.request()
may not be immediately ready for use if the parentHttp2Session
has not yet been fully established. In such cases, operationscalled on the Http2Stream
will be buffered until the 'ready'
event isemitted. User code should rarely, if ever, have need to handle the 'ready'
event directly. The ready status of an Http2Stream
can be determined bychecking the value of http2stream.id
. If the value is undefined
, the streamis not yet ready for use.
Destruction#
All Http2Stream
instances are destroyed either when:
- An
RST_STREAM
frame for the stream is received by the connected peer. - The
http2stream.rstStream()
methods is called. - The
http2stream.destroy()
orhttp2session.destroy()
methods are called.
When an Http2Stream
instance is destroyed, an attempt will be made to send anRST_STREAM
frame will be sent to the connected peer.
When the Http2Stream
instance is destroyed, the 'close'
event willbe emitted. Because Http2Stream
is an instance of stream.Duplex
, the'end'
event will also be emitted if the stream data is currently flowing.The 'error'
event may also be emitted if http2stream.destroy()
was calledwith an Error
passed as the first argument.
After the Http2Stream
has been destroyed, the http2stream.destroyed
property will be true
and the http2stream.rstCode
property will specify theRST_STREAM
error code. The Http2Stream
instance is no longer usable oncedestroyed.
Event: 'aborted'#
The 'aborted'
event is emitted whenever a Http2Stream
instance isabnormally aborted in mid-communication.
Note: The 'aborted'
event will only be emitted if the Http2Stream
writable side has not been ended.
Event: 'close'#
The 'close'
event is emitted when the Http2Stream
is destroyed. Oncethis event is emitted, the Http2Stream
instance is no longer usable.
The listener callback is passed a single argument specifying the HTTP/2 errorcode specified when closing the stream. If the code is any value other thanNGHTTP2_NO_ERROR
(0
), an 'error'
event will also be emitted.
Event: 'error'#
The 'error'
event is emitted when an error occurs during the processing ofan Http2Stream
.
Event: 'frameError'#
The 'frameError'
event is emitted when an error occurs while attempting tosend a frame. When invoked, the handler function will receive an integerargument identifying the frame type, and an integer argument identifying theerror code. The Http2Stream
instance will be destroyed immediately after the'frameError'
event is emitted.
Event: 'timeout'#
The 'timeout'
event is emitted after no activity is received for this'Http2Stream'
within the number of millseconds set usinghttp2stream.setTimeout()
.
Event: 'trailers'#
The 'trailers'
event is emitted when a block of headers associated withtrailing header fields is received. The listener callback is passed theHeaders Object and flags associated with the headers.
stream.on('trailers', (headers, flags) => { console.log(headers);});
http2stream.aborted#
Set to true
if the Http2Stream
instance was aborted abnormally. When set,the 'aborted'
event will have been emitted.
http2stream.destroyed#
Set to true
if the Http2Stream
instance has been destroyed and is no longerusable.
http2stream.priority(options)#
options
exclusive
When true
andparent
identifies a parent Stream,this stream is made the sole direct dependency of the parent, withall other existing dependents made a dependent of this stream. Default:false
parent
Specifies the numeric identifier of a stream this streamis dependent on. weight
Specifies the relative dependency of a stream in relationto other streams with the same parent
. The value is a number between1
and256
(inclusive).silent
When true
, changes the priority locally withoutsending aPRIORITY
frame to the connected peer.
- Returns:
Updates the priority for this Http2Stream
instance.
http2stream.rstCode#
Set to the RST_STREAM
error code reported when the Http2Stream
isdestroyed after either receiving an RST_STREAM
frame from the connected peer,calling http2stream.rstStream()
, or http2stream.destroy()
. Will beundefined
if the Http2Stream
has not been closed.
http2stream.rstStream(code)#
- code
Unsigned 32-bit integer identifying the error code. Default: http2.constant.NGHTTP2_NO_ERROR
(0x00
) - Returns:
Sends an RST_STREAM
frame to the connected HTTP/2 peer, causing thisHttp2Stream
to be closed on both sides using error code code
.
http2stream.rstWithNoError()#
Shortcut for http2stream.rstStream()
using error code 0x00
(No Error).
http2stream.rstWithProtocolError()#
Shortcut for http2stream.rstStream()
using error code 0x01
(Protocol Error).
http2stream.rstWithCancel()#
Shortcut for http2stream.rstStream()
using error code 0x08
(Cancel).
http2stream.rstWithRefuse()#
Shortcut for http2stream.rstStream()
using error code 0x07
(Refused Stream).
http2stream.rstWithInternalError()#
Shortcut for http2stream.rstStream()
using error code 0x02
(Internal Error).
http2stream.session#
- Value:
A reference to the Http2Session
instance that owns this Http2Stream
. Thevalue will be undefined
after the Http2Stream
instance is destroyed.
http2stream.setTimeout(msecs, callback)#
const http2 = require('http2');const client = http2.connect('http://example.org:8000');const req = client.request({ ':path': '/' });// Cancel the stream if there's no activity after 5 secondsreq.setTimeout(5000, () => req.rstWithCancel());
http2stream.state#
Provides miscellaneous information about the current state of theHttp2Stream
.
- Value:
localWindowSize
The number of bytes the connected peer may sendfor this Http2Stream
without receiving aWINDOW_UPDATE
.state
A flag indicating the low-level current state of the Http2Stream
as determined by nghttp2.localClose
true
if thisHttp2Stream
has been closed locally.remoteClose
true
if thisHttp2Stream
has been closedremotely.sumDependencyWeight
The sum weight of all Http2Stream
instances that depend on thisHttp2Stream
as specified usingPRIORITY
frames.weight
The priority weight of this Http2Stream
.
A current state of this Http2Stream
.
Class: ClientHttp2Stream#
- Extends
The ClientHttp2Stream
class is an extension of Http2Stream
that isused exclusively on HTTP/2 Clients. Http2Stream
instances on the clientprovide events such as 'response'
and 'push'
that are only relevant onthe client.
Event: 'continue'#
Emitted when the server sends a 100 Continue
status, usually becausethe request contained Expect: 100-continue
. This is an instruction thatthe client should send the request body.
Event: 'headers'#
The 'headers'
event is emitted when an additional block of headers is receivedfor a stream, such as when a block of 1xx
informational headers are received.The listener callback is passed the Headers Object and flags associated withthe headers.
stream.on('headers', (headers, flags) => { console.log(headers);});
Event: 'push'#
The 'push'
event is emitted when response headers for a Server Push streamare received. The listener callback is passed the Headers Object and flagsassociated with the headers.
stream.on('push', (headers, flags) => { console.log(headers);});
Event: 'response'#
The 'response'
event is emitted when a response HEADERS
frame has beenreceived for this stream from the connected HTTP/2 server. The listener isinvoked with two arguments: an Object containing the receivedHeaders Object, and flags associated with the headers.
For example:
const http2 = require('http2');const client = http2.connect('https://localhost');const req = client.request({ ':path': '/' });req.on('response', (headers, flags) => { console.log(headers[':status']);});
Class: ServerHttp2Stream#
- Extends:
The ServerHttp2Stream
class is an extension of Http2Stream
that isused exclusively on HTTP/2 Servers. Http2Stream
instances on the serverprovide additional methods such as http2stream.pushStream()
andhttp2stream.respond()
that are only relevant on the server.
http2stream.additionalHeaders(headers)#
headers
<Headers Object>- Returns:
Sends an additional informational HEADERS
frame to the connected HTTP/2 peer.
http2stream.headersSent#
Boolean (read-only). True if headers were sent, false otherwise.
http2stream.pushAllowed#
Read-only property mapped to the SETTINGS_ENABLE_PUSH
flag of the remoteclient's most recent SETTINGS
frame. Will be true
if the remote peeraccepts push streams, false
otherwise. Settings are the same for everyHttp2Stream
in the same Http2Session
.
http2stream.pushStream(headers[, options], callback)#
headers
<Headers Object>options
exclusive
When true
andparent
identifies a parent Stream,the created stream is made the sole direct dependency of the parent, withall other existing dependents made a dependent of the newly created stream.Default:false
parent
Specifies the numeric identifier of a stream the newlycreated stream is dependent on.
callback
Callback that is called once the push stream has beeninitiated. - Returns:
Initiates a push stream. The callback is invoked with the new Http2Stream
instance created for the push stream.
const http2 = require('http2');const server = http2.createServer();server.on('stream', (stream) => { stream.respond({ ':status': 200 }); stream.pushStream({ ':path': '/' }, (pushStream) => { pushStream.respond({ ':status': 200 }); pushStream.end('some pushed data'); }); stream.end('some data');});
Setting the weight of a push stream is not allowed in the HEADERS
frame. Passa weight
value to http2stream.priority
with the silent
option set totrue
to enable server-side bandwidth balancing between concurrent streams.
http2stream.respond([headers[, options]])#
headers
<Headers Object>options
- Returns:
const http2 = require('http2');const server = http2.createServer();server.on('stream', (stream) => { stream.respond({ ':status': 200 }); stream.end('some data');});
When set, the options.getTrailers()
function is called immediately afterqueuing the last chunk of payload data to be sent. The callback is passed asingle object (with a null
prototype) that the listener may used to specifythe trailing header fields to send to the peer.
const http2 = require('http2');const server = http2.createServer();server.on('stream', (stream) => { stream.respond({ ':status': 200 }, { getTrailers(trailers) { trailers['ABC'] = 'some value to send'; } }); stream.end('some data');});
Note: The HTTP/1 specification forbids trailers from containing HTTP/2"pseudo-header" fields (e.g. ':status'
, ':path'
, etc). An 'error'
eventwill be emitted if the getTrailers
callback attempts to set such headerfields.
http2stream.respondWithFD(fd[, headers[, options]])#
fd
A readable file descriptor. headers
<Headers Object>options
Initiates a response whose data is read from the given file descriptor. Novalidation is performed on the given file descriptor. If an error occurs whileattempting to read data using the file descriptor, the Http2Stream
will beclosed using an RST_STREAM
frame using the standard INTERNAL_ERROR
code.
When used, the Http2Stream
object's Duplex interface will be closedautomatically.
const http2 = require('http2');const fs = require('fs');const fd = fs.openSync('/some/file', 'r');const server = http2.createServer();server.on('stream', (stream) => { const stat = fs.fstatSync(fd); const headers = { 'content-length': stat.size, 'last-modified': stat.mtime.toUTCString(), 'content-type': 'text/plain' }; stream.respondWithFD(fd, headers);});server.on('close', () => fs.closeSync(fd));
The optional options.statCheck
function may be specified to give user codean opportunity to set additional content headers based on the fs.Stat
detailsof the given fd. If the statCheck
function is provided, thehttp2stream.respondWithFD()
method will perform an fs.fstat()
call tocollect details on the provided file descriptor.
The offset
and length
options may be used to limit the response to aspecific range subset. This can be used, for instance, to support HTTP Rangerequests.
When set, the options.getTrailers()
function is called immediately afterqueuing the last chunk of payload data to be sent. The callback is passed asingle object (with a null
prototype) that the listener may used to specifythe trailing header fields to send to the peer.
const http2 = require('http2');const fs = require('fs');const fd = fs.openSync('/some/file', 'r');const server = http2.createServer();server.on('stream', (stream) => { const stat = fs.fstatSync(fd); const headers = { 'content-length': stat.size, 'last-modified': stat.mtime.toUTCString(), 'content-type': 'text/plain' }; stream.respondWithFD(fd, headers, { getTrailers(trailers) { trailers['ABC'] = 'some value to send'; } });});server.on('close', () => fs.closeSync(fd));
Note: The HTTP/1 specification forbids trailers from containing HTTP/2"pseudo-header" fields (e.g. ':status'
, ':path'
, etc). An 'error'
eventwill be emitted if the getTrailers
callback attempts to set such headerfields.
http2stream.respondWithFile(path[, headers[, options]])#
path
| | headers
<Headers Object>options
Sends a regular file as the response. The path
must specify a regular fileor an 'error'
event will be emitted on the Http2Stream
object.
When used, the Http2Stream
object's Duplex interface will be closedautomatically.
The optional options.statCheck
function may be specified to give user codean opportunity to set additional content headers based on the fs.Stat
detailsof the given file:
If an error occurs while attempting to read the file data, the Http2Stream
will be closed using an RST_STREAM
frame using the standard INTERNAL_ERROR
code. If the onError
callback is defined it will be called, otherwisethe stream will be destroyed.
Example using a file path:
const http2 = require('http2');const server = http2.createServer();server.on('stream', (stream) => { function statCheck(stat, headers) { headers['last-modified'] = stat.mtime.toUTCString(); } function onError(err) { if (err.code === 'ENOENT') { stream.respond({ ':status': 404 }); } else { stream.respond({ ':status': 500 }); } stream.end(); } stream.respondWithFile('/some/file', { 'content-type': 'text/plain' }, { statCheck, onError });});
The options.statCheck
function may also be used to cancel the send operationby returning false
. For instance, a conditional request may check the statresults to determine if the file has been modified to return an appropriate304
response:
const http2 = require('http2');const server = http2.createServer();server.on('stream', (stream) => { function statCheck(stat, headers) { // Check the stat here... stream.respond({ ':status': 304 }); return false; // Cancel the send operation } stream.respondWithFile('/some/file', { 'content-type': 'text/plain' }, { statCheck });});
The content-length
header field will be automatically set.
The offset
and length
options may be used to limit the response to aspecific range subset. This can be used, for instance, to support HTTP Rangerequests.
The options.onError
function may also be used to handle all the errorsthat could happen before the delivery of the file is initiated. Thedefault behavior is to destroy the stream.
When set, the options.getTrailers()
function is called immediately afterqueuing the last chunk of payload data to be sent. The callback is passed asingle object (with a null
prototype) that the listener may used to specifythe trailing header fields to send to the peer.
const http2 = require('http2');const server = http2.createServer();server.on('stream', (stream) => { function getTrailers(trailers) { trailers['ABC'] = 'some value to send'; } stream.respondWithFile('/some/file', { 'content-type': 'text/plain' }, { getTrailers });});
Note: The HTTP/1 specification forbids trailers from containing HTTP/2"pseudo-header" fields (e.g. ':status'
, ':path'
, etc). An 'error'
eventwill be emitted if the getTrailers
callback attempts to set such headerfields.
Class: Http2Server#
- Extends:
In Http2Server
, there is no 'clientError'
event as there is inHTTP1. However, there are 'socketError'
, 'sessionError'
, and'streamError'
, for error happened on the socket, session, or streamrespectively.
Event: 'socketError'#
The 'socketError'
event is emitted when a 'socketError'
event is emitted byan Http2Session
associated with the server.
Event: 'sessionError'#
The 'sessionError'
event is emitted when an 'error'
event is emitted byan Http2Session
object. If no listener is registered for this event, an'error'
event is emitted.
Event: 'streamError'#
socket
If an ServerHttp2Stream
emits an 'error'
event, it will be forwarded here.The stream will already be destroyed when this event is triggered.
Event: 'stream'#
The 'stream'
event is emitted when a 'stream'
event has been emitted byan Http2Session
associated with the server.
const http2 = require('http2');const { HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_STATUS, HTTP2_HEADER_CONTENT_TYPE} = http2.constants;const server = http2.createServer();server.on('stream', (stream, headers, flags) => { const method = headers[HTTP2_HEADER_METHOD]; const path = headers[HTTP2_HEADER_PATH]; // ... stream.respond({ [HTTP2_HEADER_STATUS]: 200, [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain' }); stream.write('hello '); stream.end('world');});
Event: 'request'#
request
response
Emitted each time there is a request. Note that there may be multiple requestsper session. See the Compatibility API.
Event: 'timeout'#
The 'timeout'
event is emitted when there is no activity on the Server fora given number of milliseconds set using http2server.setTimeout()
.
Event: 'checkContinue'#
request
response
If a 'request'
listener is registered or http2.createServer()
issupplied a callback function, the 'checkContinue'
event is emitted each timea request with an HTTP Expect: 100-continue
is received. If this event isnot listened for, the server will automatically respond with a status100 Continue
as appropriate.
Handling this event involves calling response.writeContinue()
if the clientshould continue to send the request body, or generating an appropriate HTTPresponse (e.g. 400 Bad Request) if the client should not continue to send therequest body.
Note that when this event is emitted and handled, the 'request'
event willnot be emitted.
Class: Http2SecureServer#
- Extends:
Event: 'sessionError'#
The 'sessionError'
event is emitted when an 'error'
event is emitted byan Http2Session
object. If no listener is registered for this event, an'error'
event is emitted on the Http2Session
instance instead.
Event: 'socketError'#
The 'socketError'
event is emitted when a 'socketError'
event is emitted byan Http2Session
associated with the server.
Event: 'unknownProtocol'#
The 'unknownProtocol'
event is emitted when a connecting client fails tonegotiate an allowed protocol (i.e. HTTP/2 or HTTP/1.1). The event handlerreceives the socket for handling. If no listener is registered for this event,the connection is terminated. See the Compatibility API.
Event: 'stream'#
The 'stream'
event is emitted when a 'stream'
event has been emitted byan Http2Session
associated with the server.
const http2 = require('http2');const { HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_STATUS, HTTP2_HEADER_CONTENT_TYPE} = http2.constants;const options = getOptionsSomehow();const server = http2.createSecureServer(options);server.on('stream', (stream, headers, flags) => { const method = headers[HTTP2_HEADER_METHOD]; const path = headers[HTTP2_HEADER_PATH]; // ... stream.respond({ [HTTP2_HEADER_STATUS]: 200, [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain' }); stream.write('hello '); stream.end('world');});
Event: 'request'#
request
response
Emitted each time there is a request. Note that there may be multiple requestsper session. See the Compatibility API.
Event: 'timeout'#
Event: 'checkContinue'#
request
response
If a 'request'
listener is registered or http2.createSecureServer()
is supplied a callback function, the 'checkContinue'
event is emitted eachtime a request with an HTTP Expect: 100-continue
is received. If this eventis not listened for, the server will automatically respond with a status100 Continue
as appropriate.
Handling this event involves calling response.writeContinue()
if the clientshould continue to send the request body, or generating an appropriate HTTPresponse (e.g. 400 Bad Request) if the client should not continue to send therequest body.
Note that when this event is emitted and handled, the 'request'
event willnot be emitted.
http2.createServer(options[, onRequestHandler])#
options
maxDeflateDynamicTableSize
Sets the maximum dynamic table sizefor deflating header fields. Default: 4Kib
maxHeaderListPairs
Sets the maximum number of header entries.Default: 128
. The minimum value is4
.maxOutstandingPings
Sets the maximum number of outstanding,unacknowledged pings. The default is 10
.maxSendHeaderBlockLength
Sets the maximum allowed size for aserialized, compressed block of headers. Attempts to send headers thatexceed this limit will result in a 'frameError'
event being emittedand the stream being closed and destroyed.paddingStrategy
Identifies the strategy used for determining the amount of padding to use for HEADERS and DATA frames. Default: http2.constants.PADDING_STRATEGY_NONE
. Value may be one of:http2.constants.PADDING_STRATEGY_NONE
- Specifies that no padding isto be applied.http2.constants.PADDING_STRATEGY_MAX
- Specifies that the maximumamount of padding, as determined by the internal implementation, is tobe applied.http2.constants.PADDING_STRATEGY_CALLBACK
- Specifies that the userprovidedoptions.selectPadding
callback is to be used to determine theamount of padding.
peerMaxConcurrentStreams
Sets the maximum number of concurrentstreams for the remote peer as if a SETTINGS frame had been received. Willbe overridden if the remote peer sets its own value for. maxConcurrentStreams
. Default100
selectPadding
When options.paddingStrategy
is equal tohttp2.constants.PADDING_STRATEGY_CALLBACK
, provides the callback functionused to determine the padding. See Using options.selectPadding.settings
<Settings Object> The initial settings to send to theremote peer upon connection.
onRequestHandler
See Compatibility API - Returns:
Returns a net.Server
instance that creates and manages Http2Session
instances.
const http2 = require('http2');// Create a plain-text HTTP/2 serverconst server = http2.createServer();server.on('stream', (stream, headers) => { stream.respond({ 'content-type': 'text/html', ':status': 200 }); stream.end('Hello World
');});server.listen(80);
http2.createSecureServer(options[, onRequestHandler])#
options
allowHTTP1
Incoming client connections that do not supportHTTP/2 will be downgraded to HTTP/1.x when set to true
. Default:false
. See the'unknownProtocol'
event. See ALPN negotiation.maxDeflateDynamicTableSize
Sets the maximum dynamic table sizefor deflating header fields. Default: 4Kib
maxHeaderListPairs
Sets the maximum number of header entries.Default: 128
. The minimum value is4
.maxOutstandingPings
Sets the maximum number of outstanding,unacknowledged pings. The default is 10
.maxSendHeaderBlockLength
Sets the maximum allowed size for aserialized, compressed block of headers. Attempts to send headers thatexceed this limit will result in a 'frameError'
event being emittedand the stream being closed and destroyed.paddingStrategy
Identifies the strategy used for determining the amount of padding to use for HEADERS and DATA frames. Default: http2.constants.PADDING_STRATEGY_NONE
. Value may be one of:http2.constants.PADDING_STRATEGY_NONE
- Specifies that no padding isto be applied.http2.constants.PADDING_STRATEGY_MAX
- Specifies that the maximumamount of padding, as determined by the internal implementation, is tobe applied.http2.constants.PADDING_STRATEGY_CALLBACK
- Specifies that the userprovidedoptions.selectPadding
callback is to be used to determine theamount of padding.
peerMaxConcurrentStreams
Sets the maximum number of concurrentstreams for the remote peer as if a SETTINGS frame had been received. Willbe overridden if the remote peer sets its own value for maxConcurrentStreams
. Default:100
selectPadding
When options.paddingStrategy
is equal tohttp2.constants.PADDING_STRATEGY_CALLBACK
, provides the callback functionused to determine the padding. See Using options.selectPadding.settings
<Settings Object> The initial settings to send to theremote peer upon connection.- ...: Any
tls.createServer()
options can be provided. Forservers, the identity options (pfx
orkey
/cert
) are usually required.
onRequestHandler
See Compatibility API - Returns
Returns a tls.Server
instance that creates and manages Http2Session
instances.
const http2 = require('http2');const options = { key: fs.readFileSync('server-key.pem'), cert: fs.readFileSync('server-cert.pem')};// Create a secure HTTP/2 serverconst server = http2.createSecureServer(options);server.on('stream', (stream, headers) => { stream.respond({ 'content-type': 'text/html', ':status': 200 }); stream.end('Hello World
');});server.listen(80);
http2.connect(authority[, options][, listener])#
authority
| options
maxDeflateDynamicTableSize
Sets the maximum dynamic table sizefor deflating header fields. Default: 4Kib
maxHeaderListPairs
Sets the maximum number of header entries.Default: 128
. The minimum value is1
.maxOutstandingPings
Sets the maximum number of outstanding,unacknowledged pings. The default is 10
.maxReservedRemoteStreams
Sets the maximum number of reserved pushstreams the client will accept at any given time. Once the current number ofcurrently reserved push streams exceeds reaches this limit, new push streamssent by the server will be automatically rejected. maxSendHeaderBlockLength
Sets the maximum allowed size for aserialized, compressed block of headers. Attempts to send headers thatexceed this limit will result in a 'frameError'
event being emittedand the stream being closed and destroyed.paddingStrategy
Identifies the strategy used for determining the amount of padding to use for HEADERS and DATA frames. Default: http2.constants.PADDING_STRATEGY_NONE
. Value may be one of:http2.constants.PADDING_STRATEGY_NONE
- Specifies that no padding isto be applied.http2.constants.PADDING_STRATEGY_MAX
- Specifies that the maximumamount of padding, as determined by the internal implementation, is tobe applied.http2.constants.PADDING_STRATEGY_CALLBACK
- Specifies that the userprovidedoptions.selectPadding
callback is to be used to determine theamount of padding.
peerMaxConcurrentStreams
Sets the maximum number of concurrentstreams for the remote peer as if a SETTINGS frame had been received. Willbe overridden if the remote peer sets its own value for maxConcurrentStreams
. Default:100
selectPadding
When options.paddingStrategy
is equal tohttp2.constants.PADDING_STRATEGY_CALLBACK
, provides the callback functionused to determine the padding. See Using options.selectPadding.settings
<Settings Object> The initial settings to send to theremote peer upon connection.createConnection
An optional callback that receives the URL
instance passed toconnect
and theoptions
object, and returns anyDuplex
stream that is to be used as the connection for this session.- ...: Any
net.connect()
ortls.connect()
options can be provided.
listener
- Returns
Returns a HTTP/2 client Http2Session
instance.
const http2 = require('http2');const client = http2.connect('https://localhost:1234');/** use the client **/client.destroy();
http2.constants#
Error Codes for RST_STREAM and GOAWAY#
Value | Name | Constant |
---|---|---|
0x00 | No Error | http2.constants.NGHTTP2_NO_ERROR |
0x01 | Protocol Error | http2.constants.NGHTTP2_PROTOCOL_ERROR |
0x02 | Internal Error | http2.constants.NGHTTP2_INTERNAL_ERROR |
0x03 | Flow Control Error | http2.constants.NGHTTP2_FLOW_CONTROL_ERROR |
0x04 | Settings Timeout | http2.constants.NGHTTP2_SETTINGS_TIMEOUT |
0x05 | Stream Closed | http2.constants.NGHTTP2_STREAM_CLOSED |
0x06 | Frame Size Error | http2.constants.NGHTTP2_FRAME_SIZE_ERROR |
0x07 | Refused Stream | http2.constants.NGHTTP2_REFUSED_STREAM |
0x08 | Cancel | http2.constants.NGHTTP2_CANCEL |
0x09 | Compression Error | http2.constants.NGHTTP2_COMPRESSION_ERROR |
0x0a | Connect Error | http2.constants.NGHTTP2_CONNECT_ERROR |
0x0b | Enhance Your Calm | http2.constants.NGHTTP2_ENHANCE_YOUR_CALM |
0x0c | Inadequate Security | http2.constants.NGHTTP2_INADEQUATE_SECURITY |
0x0d | HTTP/1.1 Required | http2.constants.NGHTTP2_HTTP_1_1_REQUIRED |
The 'timeout'
event is emitted when there is no activity on the Server fora given number of milliseconds set using http2server.setTimeout()
.
http2.getDefaultSettings()#
- Returns: <Settings Object>
Returns an object containing the default settings for an Http2Session
instance. This method returns a new object instance every time it is calledso instances returned may be safely modified for use.
http2.getPackedSettings(settings)#
settings
<Settings Object>- Returns:
Returns a Buffer
instance containing serialized representation of the givenHTTP/2 settings as specified in the HTTP/2 specification. This is intendedfor use with the HTTP2-Settings
header field.
const http2 = require('http2');const packed = http2.getPackedSettings({ enablePush: false });console.log(packed.toString('base64'));// Prints: AAIAAAAA
http2.getUnpackedSettings(buf)#
buf
| The packed settings. - Returns: <Settings Object>
Returns a Settings Object containing the deserialized settings from thegiven Buffer
as generated by http2.getPackedSettings()
.
Headers Object#
Headers are represented as own-properties on JavaScript objects. The propertykeys will be serialized to lower-case. Property values should be strings (ifthey are not they will be coerced to strings) or an Array of strings (in orderto send more than one value per header field).
For example:
const headers = { ':status': '200', 'content-type': 'text-plain', 'ABC': ['has', 'more', 'than', 'one', 'value']};stream.respond(headers);
Note: Header objects passed to callback functions will have a null
prototype. This means that normal JavaScript object methods such asObject.prototype.toString()
and Object.prototype.hasOwnProperty()
willnot work.
const http2 = require('http2');const server = http2.createServer();server.on('stream', (stream, headers) => { console.log(headers[':path']); console.log(headers.ABC);});
Settings Object#
The http2.getDefaultSettings()
, http2.getPackedSettings()
,http2.createServer()
, http2.createSecureServer()
,http2session.settings()
, http2session.localSettings
, andhttp2session.remoteSettings
APIs either return or receive as input anobject that defines configuration settings for an Http2Session
object.These objects are ordinary JavaScript objects containing the followingproperties.
headerTableSize
Specifies the maximum number of bytes used forheader compression. Default: 4,096 octets
. The minimum allowedvalue is 0. The maximum allowed value is 232-1.enablePush
Specifies true
if HTTP/2 Push Streams are to bepermitted on theHttp2Session
instances.initialWindowSize
Specifies the senders initial window sizefor stream-level flow control. Default: 65,535 bytes
. The minimumallowed value is 0. The maximum allowed value is 232-1.maxFrameSize
Specifies the size of the largest frame payload.Default: 16,384 bytes
. The minimum allowed value is 16,384. The maximumallowed value is 224-1.maxConcurrentStreams
Specifies the maximum number of concurrentstreams permitted on an Http2Session
. There is no default value whichimplies, at least theoretically, 231-1 streams may be openconcurrently at any given time in anHttp2Session
. The minimum value is- The maximum allowed value is 231-1.
maxHeaderListSize
Specifies the maximum size (uncompressed octets)of header list that will be accepted. The minimum allowed value is 0. Themaximum allowed value is 232-1. Default: 65535.
All additional properties on the settings object are ignored.
Using options.selectPadding
#
When options.paddingStrategy
is equal tohttp2.constants.PADDING_STRATEGY_CALLBACK
, the HTTP/2 implementation willconsult the options.selectPadding
callback function, if provided, to determinethe specific amount of padding to use per HEADERS and DATA frame.
The options.selectPadding
function receives two numeric arguments,frameLen
and maxFrameLen
and must return a number N
such thatframeLen <= N <= maxFrameLen
.
const http2 = require('http2');const server = http2.createServer({ paddingStrategy: http2.constants.PADDING_STRATEGY_CALLBACK, selectPadding(frameLen, maxFrameLen) { return maxFrameLen; }});
Note: The options.selectPadding
function is invoked once for everyHEADERS and DATA frame. This has a definite noticeable impact onperformance.
Error Handling#
There are several types of error conditions that may arise when using thehttp2
module:
Validation Errors occur when an incorrect argument, option, or setting value ispassed in. These will always be reported by a synchronous throw
.
State Errors occur when an action is attempted at an incorrect time (forinstance, attempting to send data on a stream after it has closed). These willbe reported using either a synchronous throw
or via an 'error'
event onthe Http2Stream
, Http2Session
or HTTP/2 Server objects, depending on whereand when the error occurs.
Internal Errors occur when an HTTP/2 session fails unexpectedly. These will bereported via an 'error'
event on the Http2Session
or HTTP/2 Server objects.
Protocol Errors occur when various HTTP/2 protocol constraints are violated.These will be reported using either a synchronous throw
or via an 'error'
event on the Http2Stream
, Http2Session
or HTTP/2 Server objects, dependingon where and when the error occurs.
Invalid character handling in header names and values#
The HTTP/2 implementation applies stricter handling of invalid characters inHTTP header names and values than the HTTP/1 implementation.
Header field names are case-insensitive and are transmitted over the wirestrictly as lower-case strings. The API provided by Node.js allows headernames to be set as mixed-case strings (e.g. Content-Type
) but will convertthose to lower-case (e.g. content-type
) upon transmission.
Header field-names must only contain one or more of the following ASCIIcharacters: a
-z
, A
-Z
, 0
-9
, !
, #
, $
, %
, &
, '
, *
, +
,-
, .
, ^
, _
, `
(backtick), |
, and ~
.
Using invalid characters within an HTTP header field name will cause thestream to be closed with a protocol error being reported.
Header field values are handled with more leniency but should not containnew-line or carriage return characters and should be limited to US-ASCIIcharacters, per the requirements of the HTTP specification.
Push streams on the client#
To receive pushed streams on the client, set a listener for the 'stream'
event on the ClientHttp2Session
:
const http2 = require('http2');const client = http2.connect('http://localhost');client.on('stream', (pushedStream, requestHeaders) => { pushedStream.on('push', (responseHeaders) => { // process response headers }); pushedStream.on('data', (chunk) => { /* handle pushed data */ });});const req = client.request({ ':path': '/' });
Supporting the CONNECT method#
The CONNECT
method is used to allow an HTTP/2 server to be used as a proxyfor TCP/IP connections.
A simple TCP Server:
const net = require('net');const server = net.createServer((socket) => { let name = ''; socket.setEncoding('utf8'); socket.on('data', (chunk) => name += chunk); socket.on('end', () => socket.end(`hello ${name}`));});server.listen(8000);
An HTTP/2 CONNECT proxy:
const http2 = require('http2');const net = require('net');const { URL } = require('url');const proxy = http2.createServer();proxy.on('stream', (stream, headers) => { if (headers[':method'] !== 'CONNECT') { // Only accept CONNECT requests stream.rstWithRefused(); return; } const auth = new URL(`tcp://${headers[':authority']}`); // It's a very good idea to verify that hostname and port are // things this proxy should be connecting to. const socket = net.connect(auth.port, auth.hostname, () => { stream.respond(); socket.pipe(stream); stream.pipe(socket); }); socket.on('error', (error) => { stream.rstStream(http2.constants.NGHTTP2_CONNECT_ERROR); });});proxy.listen(8001);
An HTTP/2 CONNECT client:
const http2 = require('http2');const client = http2.connect('http://localhost:8001');// Must not specify the ':path' and ':scheme' headers// for CONNECT requests or an error will be thrown.const req = client.request({ ':method': 'CONNECT', ':authority': `localhost:${port}`});req.on('response', (headers) => { console.log(headers[http2.constants.HTTP2_HEADER_STATUS]);});let data = '';req.setEncoding('utf8');req.on('data', (chunk) => data += chunk);req.on('end', () => { console.log(`The server says: ${data}`); client.destroy();});req.end('Jane');
Compatibility API#
The Compatibility API has the goal of providing a similar developer experienceof HTTP/1 when using HTTP/2, making it possible to develop applicationsthat supports both HTTP/1 and HTTP/2. This API targets only thepublic API of the HTTP/1, however many modules uses internalmethods or state, and those are not supported as it is a completelydifferent implementation.
The following example creates an HTTP/2 server using the compatibilityAPI:
const http2 = require('http2');const server = http2.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.setHeader('X-Foo', 'bar'); res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('ok');});
In order to create a mixed HTTPS and HTTP/2 server, refer to theALPN negotiation section.Upgrading from non-tls HTTP/1 servers is not supported.
The HTTP2 compatibility API is composed of Http2ServerRequest
andHttp2ServerResponse
. They aim at API compatibility with HTTP/1, butthey do not hide the differences between the protocols. As an example,the status message for HTTP codes is ignored.
ALPN negotiation#
ALPN negotiation allows to support both HTTPS and HTTP/2 overthe same socket. The req
and res
objects can be either HTTP/1 orHTTP/2, and an application must restrict itself to the public API ofHTTP/1, and detect if it is possible to use the more advancedfeatures of HTTP/2.
The following example creates a server that supports both protocols:
const { createSecureServer } = require('http2');const { readFileSync } = require('fs');const cert = readFileSync('./cert.pem');const key = readFileSync('./key.pem');const server = createSecureServer( { cert, key, allowHTTP1: true }, onRequest).listen(4443);function onRequest(req, res) { // detects if it is a HTTPS request or HTTP/2 const { socket: { alpnProtocol } } = req.httpVersion === '2.0' ? req.stream.session : req; res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify({ alpnProtocol, httpVersion: req.httpVersion }));}
The 'request'
event works identically on both HTTPS andHTTP/2.
Class: http2.Http2ServerRequest#
A Http2ServerRequest
object is created by http2.Server
orhttp2.SecureServer
and passed as the first argument to the'request'
event. It may be used to access a request status, headers anddata.
It implements the Readable Stream interface, as well as thefollowing additional events, methods, and properties.
Event: 'aborted'#
The 'aborted'
event is emitted whenever a Http2ServerRequest
instance isabnormally aborted in mid-communication.
Note: The 'aborted'
event will only be emitted if theHttp2ServerRequest
writable side has not been ended.
Event: 'close'#
Indicates that the underlying Http2Stream
was closed.Just like 'end'
, this event occurs only once per response.
request.destroy([error])#
Calls destroy()
on the Http2Stream
that receivedthe Http2ServerRequest
. If error
is provided, an 'error'
eventis emitted and error
is passed as an argument to any listeners on the event.
It does nothing if the stream was already destroyed.
request.headers#
The request/response headers object.
Key-value pairs of header names and values. Header names are lower-cased.Example:
// Prints something like://// { 'user-agent': 'curl/7.22.0',// host: '127.0.0.1:8000',// accept: '*/*' }console.log(request.headers);
See Headers Object.
Note: In HTTP/2, the request path, host name, protocol, and method arerepresented as special headers prefixed with the :
character (e.g. ':path'
).These special headers will be included in the request.headers
object. Caremust be taken not to inadvertently modify these special headers or errors mayoccur. For instance, removing all headers from the request will cause errorsto occur:
removeAllHeaders(request.headers);assert(request.url); // Fails because the :path header has been removed
request.httpVersion#
In case of server request, the HTTP version sent by the client. In the case ofclient response, the HTTP version of the connected-to server. Returns'2.0'
.
Also message.httpVersionMajor
is the first integer andmessage.httpVersionMinor
is the second.
request.method#
The request method as a string. Read only. Example:'GET'
, 'DELETE'
.
request.rawHeaders#
The raw request/response headers list exactly as they were received.
Note that the keys and values are in the same list. It is not alist of tuples. So, the even-numbered offsets are key values, and theodd-numbered offsets are the associated values.
Header names are not lowercased, and duplicates are not merged.
// Prints something like://// [ 'user-agent',// 'this is invalid because there can be only one',// 'User-Agent',// 'curl/7.22.0',// 'Host',// '127.0.0.1:8000',// 'ACCEPT',// '*/*' ]console.log(request.rawHeaders);
request.rawTrailers#
The raw request/response trailer keys and values exactly as they werereceived. Only populated at the 'end'
event.
request.setTimeout(msecs, callback)#
Sets the Http2Stream
's timeout value to msecs
. If a callback isprovided, then it is added as a listener on the 'timeout'
event onthe response object.
If no 'timeout'
listener is added to the request, the response, orthe server, then Http2Stream
s are destroyed when they time out. If ahandler is assigned to the request, the response, or the server's 'timeout'
events, timed out sockets must be handled explicitly.
Returns request
.
request.socket#
Returns a Proxy object that acts as a net.Socket
(or tls.TLSSocket
) butapplies getters, setters, and methods based on HTTP/2 logic.
destroyed
, readable
, and writable
properties will be retrieved from andset on request.stream
.
destroy
, emit
, end
, on
and once
methods will be called onrequest.stream
.
setTimeout
method will be called on request.stream.session
.
pause
, read
, resume
, and write
will throw an error with codeERR_HTTP2_NO_SOCKET_MANIPULATION
. See Http2Session and Sockets formore information.
All other interactions will be routed directly to the socket. With TLS support,use request.socket.getPeerCertificate()
to obtain the client'sauthentication details.
request.stream#
The Http2Stream
object backing the request.
request.trailers#
The request/response trailers object. Only populated at the 'end'
event.
request.url#
Request URL string. This contains only the URL that ispresent in the actual HTTP request. If the request is:
GET /status?name=ryan HTTP/1.1\r\nAccept: text/plain\r\n\r\n
Then request.url
will be:
'/status?name=ryan'
To parse the url into its parts require('url').parse(request.url)
can be used. Example:
$ node> require('url').parse('/status?name=ryan')Url { protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: '?name=ryan', query: 'name=ryan', pathname: '/status', path: '/status?name=ryan', href: '/status?name=ryan' }
To extract the parameters from the query string, therequire('querystring').parse
function can be used, ortrue
can be passed as the second argument to require('url').parse
.Example:
$ node> require('url').parse('/status?name=ryan', true)Url { protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: '?name=ryan', query: { name: 'ryan' }, pathname: '/status', path: '/status?name=ryan', href: '/status?name=ryan' }
Class: http2.Http2ServerResponse#
This object is created internally by an HTTP server--not by the user. It ispassed as the second parameter to the 'request'
event.
The response implements, but does not inherit from, the Writable Streaminterface. This is an EventEmitter
with the following events:
Event: 'close'#
Indicates that the underlying Http2Stream
was terminated beforeresponse.end()
was called or able to flush.
Event: 'finish'#
Emitted when the response has been sent. More specifically, this event isemitted when the last segment of the response headers and body have beenhanded off to the HTTP/2 multiplexing for transmission over the network. Itdoes not imply that the client has received anything yet.
After this event, no more events will be emitted on the response object.
response.addTrailers(headers)#
This method adds HTTP trailing headers (a header but at the end of themessage) to the response.
Attempting to set a header field name or value that contains invalid characterswill result in a TypeError
being thrown.
response.connection#
See response.socket
.
response.end([data][, encoding][, callback])#
This method signals to the server that all of the response headers and bodyhave been sent; that server should consider this message complete.The method, response.end()
, MUST be called on each response.
If data
is specified, it is equivalent to callingresponse.write(data, encoding)
followed by response.end(callback)
.
If callback
is specified, it will be called when the response streamis finished.
response.finished#
Boolean value that indicates whether the response has completed. Startsas false
. After response.end()
executes, the value will be true
.
response.getHeader(name)#
Reads out a header that has already been queued but not sent to the client.Note that the name is case insensitive.
Example:
const contentType = response.getHeader('content-type');
response.getHeaderNames()#
Returns an array containing the unique names of the current outgoing headers.All header names are lowercase.
Example:
response.setHeader('Foo', 'bar');response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);const headerNames = response.getHeaderNames();// headerNames === ['foo', 'set-cookie']
response.getHeaders()#
Returns a shallow copy of the current outgoing headers. Since a shallow copyis used, array values may be mutated without additional calls to variousheader-related http module methods. The keys of the returned object are theheader names and the values are the respective header values. All header namesare lowercase.
Note: The object returned by the response.getHeaders()
method does notprototypically inherit from the JavaScript Object
. This means that typicalObject
methods such as obj.toString()
, obj.hasOwnProperty()
, and othersare not defined and will not work.
Example:
response.setHeader('Foo', 'bar');response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);const headers = response.getHeaders();// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }
response.hasHeader(name)#
Returns true
if the header identified by name
is currently set in theoutgoing headers. Note that the header name matching is case-insensitive.
Example:
const hasContentType = response.hasHeader('content-type');
response.headersSent#
Boolean (read-only). True if headers were sent, false otherwise.
response.removeHeader(name)#
Removes a header that has been queued for implicit sending.
Example:
response.removeHeader('Content-Encoding');
response.sendDate#
When true, the Date header will be automatically generated and sent inthe response if it is not already present in the headers. Defaults to true.
This should only be disabled for testing; HTTP requires the Date headerin responses.
response.setHeader(name, value)#
Sets a single header value for implicit headers. If this header already existsin the to-be-sent headers, its value will be replaced. Use an array of stringshere to send multiple headers with the same name.
Example:
response.setHeader('Content-Type', 'text/html');
or
response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
Attempting to set a header field name or value that contains invalid characterswill result in a TypeError
being thrown.
When headers have been set with response.setHeader()
, they will be mergedwith any headers passed to response.writeHead()
, with the headers passedto response.writeHead()
given precedence.
// returns content-type = text/plainconst server = http2.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.setHeader('X-Foo', 'bar'); res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('ok');});
response.setTimeout(msecs[, callback])#
Sets the Http2Stream
's timeout value to msecs
. If a callback isprovided, then it is added as a listener on the 'timeout'
event onthe response object.
If no 'timeout'
listener is added to the request, the response, orthe server, then Http2Stream
s are destroyed when they time out. If ahandler is assigned to the request, the response, or the server's 'timeout'
events, timed out sockets must be handled explicitly.
Returns response
.
response.socket#
Returns a Proxy object that acts as a net.Socket
(or tls.TLSSocket
) butapplies getters, setters, and methods based on HTTP/2 logic.
destroyed
, readable
, and writable
properties will be retrieved from andset on response.stream
.
destroy
, emit
, end
, on
and once
methods will be called onresponse.stream
.
setTimeout
method will be called on response.stream.session
.
pause
, read
, resume
, and write
will throw an error with codeERR_HTTP2_NO_SOCKET_MANIPULATION
. See Http2Session and Sockets formore information.
All other interactions will be routed directly to the socket.
Example:
const http2 = require('http2');const server = http2.createServer((req, res) => { const ip = req.socket.remoteAddress; const port = req.socket.remotePort; res.end(`Your IP address is ${ip} and your source port is ${port}.`);}).listen(3000);
response.statusCode#
When using implicit headers (not calling response.writeHead()
explicitly),this property controls the status code that will be sent to the client whenthe headers get flushed.
Example:
response.statusCode = 404;
After response header was sent to the client, this property indicates thestatus code which was sent out.
response.statusMessage#
Status message is not supported by HTTP/2 (RFC7540 8.1.2.4). It returnsan empty string.
response.stream#
The Http2Stream
object backing the response.
response.write(chunk[, encoding][, callback])#
If this method is called and response.writeHead()
has not been called,it will switch to implicit header mode and flush the implicit headers.
This sends a chunk of the response body. This method maybe called multiple times to provide successive parts of the body.
Note that in the http
module, the response body is omitted when therequest is a HEAD request. Similarly, the 204
and 304
responsesmust not include a message body.
chunk
can be a string or a buffer. If chunk
is a string,the second parameter specifies how to encode it into a byte stream.By default the encoding
is 'utf8'
. callback
will be called when this chunkof data is flushed.
Note: This is the raw HTTP body and has nothing to do withhigher-level multi-part body encodings that may be used.
The first time response.write()
is called, it will send the bufferedheader information and the first chunk of the body to the client. The secondtime response.write()
is called, Node.js assumes data will be streamed,and sends the new data separately. That is, the response is buffered up to thefirst chunk of the body.
Returns true
if the entire data was flushed successfully to the kernelbuffer. Returns false
if all or part of the data was queued in user memory.'drain'
will be emitted when the buffer is free again.
response.writeContinue()#
Sends a status 100 Continue
to the client, indicating that the request bodyshould be sent. See the 'checkContinue'
event on Http2Server
andHttp2SecureServer
.
response.writeHead(statusCode[, statusMessage][, headers])#
Sends a response header to the request. The status code is a 3-digit HTTPstatus code, like 404
. The last argument, headers
, are the response headers.
For compatibility with HTTP/1, a human-readable statusMessage
may bepassed as the second argument. However, because the statusMessage
has nomeaning within HTTP/2, the argument will have no effect and a process warningwill be emitted.
Example:
const body = 'hello world';response.writeHead(200, { 'Content-Length': Buffer.byteLength(body), 'Content-Type': 'text/plain' });
Note that Content-Length is given in bytes not characters. TheBuffer.byteLength()
API may be used to determine the number of bytes in agiven encoding. On outbound messages, Node.js does not check if Content-Lengthand the length of the body being transmitted are equal or not. However, whenreceiving messages, Node.js will automatically reject messages when theContent-Length does not match the actual payload size.
This method may be called at most one time on a message beforeresponse.end()
is called.
If response.write()
or response.end()
are called before callingthis, the implicit/mutable headers will be calculated and call this function.
When headers have been set with response.setHeader()
, they will be mergedwith any headers passed to response.writeHead()
, with the headers passedto response.writeHead()
given precedence.
// returns content-type = text/plainconst server = http2.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.setHeader('X-Foo', 'bar'); res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('ok');});
Attempting to set a header field name or value that contains invalid characterswill result in a TypeError
being thrown.
response.createPushResponse(headers, callback)#
Call http2stream.pushStream()
with the given headers, and wraps thegiven newly created Http2Stream
on Http2ServerRespose
.
The callback will be called with an error with code ERR_HTTP2_STREAM_CLOSED
if the stream is closed.