HTTP
Table des matières
- Class: http.Agent
- Class: http.ClientRequest
- Event: 'abort'
- Event: 'close'
- Event: 'connect'
- Event: 'continue'
- Event: 'finish'
- Event: 'information'
- Event: 'response'
- Event: 'socket'
- Event: 'timeout'
- Event: 'upgrade'
- request.abort()
- request.aborted
- request.connection
- request.cork()
- request.end([data[, encoding]][, callback])
- request.destroy([error])
- request.finished
- request.flushHeaders()
- request.getHeader(name)
- request.getHeaderNames()
- request.getHeaders()
- request.getRawHeaderNames()
- request.hasHeader(name)
- request.maxHeadersCount
- request.path
- request.method
- request.host
- request.protocol
- request.removeHeader(name)
- request.reusedSocket
- request.setHeader(name, value)
- request.setNoDelay([noDelay])
- request.setSocketKeepAlive([enable][, initialDelay])
- request.setTimeout(timeout[, callback])
- request.socket
- request.uncork()
- request.writableEnded
- request.writableFinished
- request.write(chunk[, encoding][, callback])
- Class: http.Server
- Event: 'checkContinue'
- Event: 'checkExpectation'
- Event: 'clientError'
- Event: 'close'
- Event: 'connect'
- Event: 'connection'
- Event: 'dropRequest'
- Event: 'request'
- Event: 'upgrade'
- server.close([callback])
- server.closeAllConnections()
- server.closeIdleConnections()
- server.headersTimeout
- server.listen()
- server.listening
- server.maxHeadersCount
- server.requestTimeout
- server.setTimeout([msecs][, callback])
- server.maxRequestsPerSocket
- server.timeout
- server.keepAliveTimeout
- Class: http.ServerResponse
- Event: 'close'
- Event: 'finish'
- response.addTrailers(headers)
- response.connection
- response.cork()
- response.end([data[, encoding]][, callback])
- response.finished
- response.flushHeaders()
- response.getHeader(name)
- response.getHeaderNames()
- response.getHeaders()
- response.hasHeader(name)
- response.headersSent
- response.removeHeader(name)
- response.req
- response.sendDate
- response.setHeader(name, value)
- response.setTimeout(msecs[, callback])
- response.socket
- response.statusCode
- response.statusMessage
- response.uncork()
- response.writableEnded
- response.writableFinished
- response.write(chunk[, encoding][, callback])
- response.writeContinue()
- response.writeEarlyHints(hints[, callback])
- response.writeHead(statusCode[, statusMessage][, headers])
- response.writeProcessing()
- Class: http.IncomingMessage
- Event: 'aborted'
- Event: 'close'
- message.aborted
- message.complete
- message.connection
- message.destroy([error])
- message.headers
- message.headersDistinct
- message.httpVersion
- message.method
- message.rawHeaders
- message.rawTrailers
- message.setTimeout(msecs[, callback])
- message.socket
- message.statusCode
- message.statusMessage
- message.trailers
- message.trailersDistinct
- message.url
- Class: http.OutgoingMessage
- Event: 'drain'
- Event: 'finish'
- Event: 'prefinish'
- outgoingMessage.addTrailers(headers)
- outgoingMessage.appendHeader(name, value)
- outgoingMessage.connection
- outgoingMessage.cork()
- outgoingMessage.destroy([error])
- outgoingMessage.end(chunk[, encoding][, callback])
- outgoingMessage.flushHeaders()
- outgoingMessage.getHeader(name)
- outgoingMessage.getHeaderNames()
- outgoingMessage.getHeaders()
- outgoingMessage.hasHeader(name)
- outgoingMessage.headersSent
- outgoingMessage.pipe()
- outgoingMessage.removeHeader(name)
- outgoingMessage.setHeader(name, value)
- outgoingMessage.setTimeout(msesc[, callback])
- outgoingMessage.socket
- outgoingMessage.uncork()
- outgoingMessage.writableCorked
- outgoingMessage.writableEnded
- outgoingMessage.writableFinished
- outgoingMessage.writableHighWaterMark
- outgoingMessage.writableLength
- outgoingMessage.writableObjectMode
- outgoingMessage.write(chunk[, encoding][, callback])
- http.METHODS
- http.STATUS_CODES
- http.createServer([options][, requestListener])
- http.get(options[, callback])
- http.get(url[, options][, callback])
- http.globalAgent
- http.maxHeaderSize
- http.request(options[, callback])
- http.request(url[, options][, callback])
- http.validateHeaderName(name)
- http.validateHeaderValue(name, value)
- http.setMaxIdleHTTPParsers
Ajouté en: v0.10.0
Code source: lib/http.js
To use the HTTP server and client one must require('node:http')
.
The HTTP interfaces in Node.js are designed to support many features of the protocol which have been traditionally difficult to use. In particular, large, possibly chunk-encoded, messages. The interface is careful to never buffer entire requests or responses, so the user is able to stream data.
HTTP message headers are represented by an object like this:
JS
Keys are lowercased. Values are not modified.
In order to support the full spectrum of possible HTTP applications, the Node.js HTTP API is very low-level. It deals with stream handling and message parsing only. It parses a message into headers and body but it does not parse the actual headers or the body.
See message.headers
for details on how duplicate headers are handled.
The raw headers as they were received are retained in the rawHeaders
property, which is an array of [key, value, key2, value2, ...]
. For
example, the previous message header object might have a rawHeaders
list like the following:
JS
C http.Agent
Ajouté en: v0.3.4
An Agent
is responsible for managing connection persistence
and reuse for HTTP clients. It maintains a queue of pending requests
for a given host and port, reusing a single socket connection for each
until the queue is empty, at which time the socket is either destroyed
or put into a pool where it is kept to be used again for requests to the
same host and port. Whether it is destroyed or pooled depends on the
keepAlive
option.
Pooled connections have TCP Keep-Alive enabled for them, but servers may
still close idle connections, in which case they will be removed from the
pool and a new connection will be made when a new HTTP request is made for
that host and port. Servers may also refuse to allow multiple requests
over the same connection, in which case the connection will have to be
remade for every request and cannot be pooled. The Agent
will still make
the requests to that server, but each one will occur over a new connection.
When a connection is closed by the client or the server, it is removed
from the pool. Any unused sockets in the pool will be unrefed so as not
to keep the Node.js process running when there are no outstanding requests.
(see socket.unref()
).
It is good practice, to destroy()
an Agent
instance when it is no
longer in use, because unused sockets consume OS resources.
Sockets are removed from an agent when the socket emits either
a 'close'
event or an 'agentRemove'
event. When intending to keep one
HTTP request open for a long time without keeping it in the agent, something
like the following may be done:
JS
An agent may also be used for an individual request. By providing
{agent: false}
as an option to the http.get()
or http.request()
functions, a one-time use Agent
with default options will be used
for the client connection.
agent:false
:
JS
M new Agent([options])
Historique
Version | Changements |
---|---|
v15.6.0, v14.17.0 | Change the default scheduling from 'fifo' to 'lifo'. |
v14.5.0, v12.19.0 | Add `maxTotalSockets` option to agent constructor. |
v14.5.0, v12.20.0 | Add `scheduling` option to specify the free socket scheduling strategy. |
v0.3.4 | Ajouté en: v0.3.4 |
options
Object
Set of configurable options to set on the agent. Can have the following fields:keepAlive
boolean
Keep sockets around even when there are no outstanding requests, so they can be used for future requests without having to reestablish a TCP connection. Not to be confused with thekeep-alive
value of theConnection
header. TheConnection: keep-alive
header is always sent when using an agent except when theConnection
header is explicitly specified or when thekeepAlive
andmaxSockets
options are respectively set tofalse
andInfinity
, in which caseConnection: close
will be used. Default:false
.keepAliveMsecs
number
When using thekeepAlive
option, specifies the initial delay for TCP Keep-Alive packets. Ignored when thekeepAlive
option isfalse
orundefined
. Default:1000
.maxSockets
number
Maximum number of sockets to allow per host. If the same host opens multiple concurrent connections, each request will use new socket until themaxSockets
value is reached. If the host attempts to open more connections thanmaxSockets
, the additional requests will enter into a pending request queue, and will enter active connection state when an existing connection terminates. This makes sure there are at mostmaxSockets
active connections at any point in time, from a given host. Default:Infinity
.maxTotalSockets
number
Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default:Infinity
.maxFreeSockets
number
Maximum number of sockets per host to leave open in a free state. Only relevant ifkeepAlive
is set totrue
. Default:256
.scheduling
string
Scheduling strategy to apply when picking the next free socket to use. It can be'fifo'
or'lifo'
. The main difference between the two scheduling strategies is that'lifo'
selects the most recently used socket, while'fifo'
selects the least recently used socket. In case of a low rate of request per second, the'lifo'
scheduling will lower the risk of picking a socket that might have been closed by the server due to inactivity. In case of a high rate of request per second, the'fifo'
scheduling will maximize the number of open sockets, while the'lifo'
scheduling will keep it as low as possible. Default:'lifo'
.timeout
number
Socket timeout in milliseconds. This will set the timeout when the socket is created.
options
in socket.connect()
are also supported.
The default http.globalAgent
that is used by http.request()
has all
of these values set to their respective defaults.
To configure any of them, a custom http.Agent
instance must be created.
JS
M agent.createConnection(options[, callback])
Ajouté en: v0.11.4
options
Object
Options containing connection details. Checknet.createConnection()
for the format of the optionscallback
Function
Callback function that receives the created socket- Returns:
stream.Duplex
Produces a socket/stream to be used for HTTP requests.
By default, this function is the same as net.createConnection()
. However,
custom agents may override this method in case greater flexibility is desired.
A socket/stream can be supplied in one of two ways: by returning the
socket/stream from this function, or by passing the socket/stream to callback
.
This method is guaranteed to return an instance of the net.Socket
class,
a subclass of stream.Duplex
, unless the user specifies a socket
type other than net.Socket
.
callback
has a signature of (err, stream)
.
M agent.keepSocketAlive(socket)
Ajouté en: v8.1.0
socket
stream.Duplex
Called when socket
is detached from a request and could be persisted by the
Agent
. Default behavior is to:
JS
This method can be overridden by a particular Agent
subclass. If this
method returns a falsy value, the socket will be destroyed instead of persisting
it for use with the next request.
The socket
argument can be an instance of net.Socket
, a subclass of
stream.Duplex
.
M agent.reuseSocket(socket, request)
Ajouté en: v8.1.0
socket
stream.Duplex
request
http.ClientRequest
Called when socket
is attached to request
after being persisted because of
the keep-alive options. Default behavior is to:
JS
This method can be overridden by a particular Agent
subclass.
The socket
argument can be an instance of net.Socket
, a subclass of
stream.Duplex
.
M agent.destroy()
Ajouté en: v0.11.4
Destroy any sockets that are currently in use by the agent.
It is usually not necessary to do this. However, if using an
agent with keepAlive
enabled, then it is best to explicitly shut down
the agent when it is no longer needed. Otherwise,
sockets might stay open for quite a long time before the server
terminates them.
M agent.freeSockets
Historique
Version | Changements |
---|---|
v16.0.0 | The property now has a `null` prototype. |
v0.11.4 | Ajouté en: v0.11.4 |
An object which contains arrays of sockets currently awaiting use by
the agent when keepAlive
is enabled. Do not modify.
Sockets in the freeSockets
list will be automatically destroyed and
removed from the array on 'timeout'
.
M agent.getName([options])
Historique
Version | Changements |
---|---|
v17.7.0 | The `options` parameter is now optional. |
v0.11.4 | Ajouté en: v0.11.4 |
Get a unique name for a set of request options, to determine whether a
connection can be reused. For an HTTP agent, this returns
host:port:localAddress
or host:port:localAddress:family
. For an HTTPS agent,
the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options
that determine socket reusability.
M agent.maxFreeSockets
Ajouté en: v0.11.7
By default set to 256. For agents with keepAlive
enabled, this
sets the maximum number of sockets that will be left open in the free
state.
M agent.maxSockets
Ajouté en: v0.3.6
By default set to Infinity
. Determines how many concurrent sockets the agent
can have open per origin. Origin is the returned value of agent.getName()
.
M agent.maxTotalSockets
Ajouté en: v14.5.0, v12.19.0
By default set to Infinity
. Determines how many concurrent sockets the agent
can have open. Unlike maxSockets
, this parameter applies across all origins.
M agent.requests
Historique
Version | Changements |
---|---|
v16.0.0 | The property now has a `null` prototype. |
v0.5.9 | Ajouté en: v0.5.9 |
An object which contains queues of requests that have not yet been assigned to sockets. Do not modify.
M agent.sockets
Historique
Version | Changements |
---|---|
v16.0.0 | The property now has a `null` prototype. |
v0.3.6 | Ajouté en: v0.3.6 |
An object which contains arrays of sockets currently in use by the agent. Do not modify.
C http.ClientRequest
Ajouté en: v0.1.17
- Extends:
http.OutgoingMessage
This object is created internally and returned from http.request()
. It
represents an in-progress request whose header has already been queued. The
header is still mutable using the setHeader(name, value)
,
getHeader(name)
, removeHeader(name)
API. The actual header will
be sent along with the first data chunk or when calling request.end()
.
To get the response, add a listener for 'response'
to the request object.
'response'
will be emitted from the request object when the response
headers have been received. The 'response'
event is executed with one
argument which is an instance of http.IncomingMessage
.
During the 'response'
event, one can add listeners to the
response object; particularly to listen for the 'data'
event.
If no 'response'
handler is added, then the response will be
entirely discarded. However, if a 'response'
event handler is added,
then the data from the response object must be consumed, either by
calling response.read()
whenever there is a 'readable'
event, or
by adding a 'data'
handler, or by calling the .resume()
method.
Until the data is consumed, the 'end'
event will not fire. Also, until
the data is read it will consume memory that can eventually lead to a
'process out of memory' error.
For backward compatibility, res
will only emit 'error'
if there is an
'error'
listener registered.
Set Content-Length
header to limit the response body size. Mismatching the
Content-Length
header value will result in an [Error
][] being thrown,
identified by code:
'ERR_HTTP_CONTENT_LENGTH_MISMATCH'
.
Content-Length
value should be in bytes, not characters. Use
Buffer.byteLength()
to determine the length of the body in bytes.
E 'abort'
Déprécié en: v17.0.0, v16.12.0
Emitted when the request has been aborted by the client. This event is only
emitted on the first call to abort()
.
E 'close'
Ajouté en: v0.5.4
Indicates that the request is completed, or its underlying connection was terminated prematurely (before the response completion).
E 'connect'
Ajouté en: v0.7.0
response
http.IncomingMessage
socket
stream.Duplex
head
Buffer
Emitted each time a server responds to a request with a CONNECT
method. If
this event is not being listened for, clients receiving a CONNECT
method will
have their connections closed.
This event is guaranteed to be passed an instance of the net.Socket
class,
a subclass of stream.Duplex
, unless the user specifies a socket
type other than net.Socket
.
A client and server pair demonstrating how to listen for the 'connect'
event:
JS
E 'continue'
Ajouté en: v0.3.2
Emitted when the server sends a '100 Continue' HTTP response, usually because the request contained 'Expect: 100-continue'. This is an instruction that the client should send the request body.
E 'finish'
Ajouté en: v0.3.6
Emitted when the request has been sent. More specifically, this event is emitted when the last segment of the response headers and body have been handed off to the operating system for transmission over the network. It does not imply that the server has received anything yet.
E 'information'
Ajouté en: v10.0.0
info
Object
Emitted when the server sends a 1xx intermediate response (excluding 101 Upgrade). The listeners of this event will receive an object containing the HTTP version, status code, status message, key-value headers object, and array with the raw header names followed by their respective values.
JS
101 Upgrade statuses do not fire this event due to their break from the
traditional HTTP request/response chain, such as web sockets, in-place TLS
upgrades, or HTTP 2.0. To be notified of 101 Upgrade notices, listen for the
'upgrade'
event instead.
E 'response'
Ajouté en: v0.1.0
response
http.IncomingMessage
Emitted when a response is received to this request. This event is emitted only once.
E 'socket'
Ajouté en: v0.5.3
socket
stream.Duplex
This event is guaranteed to be passed an instance of the net.Socket
class,
a subclass of stream.Duplex
, unless the user specifies a socket
type other than net.Socket
.
E 'timeout'
Ajouté en: v0.7.8
Emitted when the underlying socket times out from inactivity. This only notifies that the socket has been idle. The request must be destroyed manually.
See also: request.setTimeout()
.
E 'upgrade'
Ajouté en: v0.1.94
response
http.IncomingMessage
socket
stream.Duplex
head
Buffer
Emitted each time a server responds to a request with an upgrade. If this event is not being listened for and the response status code is 101 Switching Protocols, clients receiving an upgrade header will have their connections closed.
This event is guaranteed to be passed an instance of the net.Socket
class,
a subclass of stream.Duplex
, unless the user specifies a socket
type other than net.Socket
.
A client server pair demonstrating how to listen for the 'upgrade'
event.
JS
M request.abort()
Déprécié en: v14.1.0, v13.14.0
Marks the request as aborting. Calling this will cause remaining data in the response to be dropped and the socket to be destroyed.
M request.aborted
Historique
Version | Changements |
---|---|
v11.0.0 | The `aborted` property is no longer a timestamp number. |
v17.0.0, v16.12.0 | Ajouté en: v17.0.0, v16.12.0 |
The request.aborted
property will be true
if the request has
been aborted.
M request.connection
Déprécié en: v13.0.0
See request.socket
.
M request.cork()
Ajouté en: v13.2.0, v12.16.0
See writable.cork()
.
M request.end([data[, encoding]][, callback])
Historique
Version | Changements |
---|---|
v10.0.0 | This method now returns a reference to `ClientRequest`. |
v0.1.90 | Ajouté en: v0.1.90 |
Finishes sending the request. If any parts of the body are
unsent, it will flush them to the stream. If the request is
chunked, this will send the terminating '0\r\n\r\n'
.
If data
is specified, it is equivalent to calling
request.write(data, encoding)
followed by request.end(callback)
.
If callback
is specified, it will be called when the request stream
is finished.
M request.destroy([error])
Historique
Version | Changements |
---|---|
v14.5.0 | The function returns `this` for consistency with other Readable streams. |
v0.3.0 | Ajouté en: v0.3.0 |
Destroy the request. Optionally emit an 'error'
event,
and emit a 'close'
event. Calling this will cause remaining data
in the response to be dropped and the socket to be destroyed.
See writable.destroy()
for further details.
M request.destroyed
Ajouté en: v14.1.0, v13.14.0
Is true
after request.destroy()
has been called.
See writable.destroyed
for further details.
M request.finished
Déprécié en: v13.4.0, v12.16.0
The request.finished
property will be true
if request.end()
has been called. request.end()
will automatically be called if the
request was initiated via http.get()
.
M request.flushHeaders()
Ajouté en: v1.6.0
Flushes the request headers.
For efficiency reasons, Node.js normally buffers the request headers until
request.end()
is called or the first chunk of request data is written. It
then tries to pack the request headers and data into a single TCP packet.
That's usually desired (it saves a TCP round-trip), but not when the first
data is not sent until possibly much later. request.flushHeaders()
bypasses
the optimization and kickstarts the request.
M request.getHeader(name)
Ajouté en: v1.6.0
Reads out a header on the request. The name is case-insensitive.
The type of the return value depends on the arguments provided to
request.setHeader()
.
JS
M request.getHeaderNames()
Ajouté en: v7.7.0
- Returns: string[]
Returns an array containing the unique names of the current outgoing headers. All header names are lowercase.
JS
M request.getHeaders()
Ajouté en: v7.7.0
- Returns:
Object
Returns a shallow copy of the current outgoing headers. Since a shallow copy is used, array values may be mutated without additional calls to various header-related http module methods. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase.
The object returned by the request.getHeaders()
method does not
prototypically inherit from the JavaScript Object
. This means that typical
Object
methods such as obj.toString()
, obj.hasOwnProperty()
, and others
are not defined and will not work.
JS
M request.getRawHeaderNames()
Ajouté en: v15.13.0, v14.17.0
- Returns: string[]
Returns an array containing the unique names of the current outgoing raw headers. Header names are returned with their exact casing being set.
JS
M request.hasHeader(name)
Ajouté en: v7.7.0
Returns true
if the header identified by name
is currently set in the
outgoing headers. The header name matching is case-insensitive.
JS
M request.maxHeadersCount
number
Default:2000
Limits maximum response headers count. If set to 0, no limit will be applied.
M request.path
Ajouté en: v0.4.0
string
The request path.
M request.method
Ajouté en: v0.1.97
string
The request method.
M request.host
Ajouté en: v14.5.0, v12.19.0
string
The request host.
M request.protocol
Ajouté en: v14.5.0, v12.19.0
string
The request protocol.
M request.removeHeader(name)
Ajouté en: v1.6.0
name
string
Removes a header that's already defined into headers object.
JS
M request.reusedSocket
Ajouté en: v13.0.0, v12.16.0
boolean
Whether the request is send through a reused socket.
When sending request through a keep-alive enabled agent, the underlying socket might be reused. But if server closes connection at unfortunate time, client may run into a 'ECONNRESET' error.
JS
By marking a request whether it reused socket or not, we can do automatic error retry base on it.
JS
M request.setHeader(name, value)
Ajouté en: v1.6.0
Sets a single header value for headers object. If this header already exists in
the to-be-sent headers, its value will be replaced. Use an array of strings
here to send multiple headers with the same name. Non-string values will be
stored without modification. Therefore, request.getHeader()
may return
non-string values. However, the non-string values will be converted to strings
for network transmission.
JS
or
JS
When the value is a string an exception will be thrown if it contains
characters outside the latin1
encoding.
If you need to pass UTF-8 characters in the value please encode the value using the RFC 8187 standard.
JS
M request.setNoDelay([noDelay])
Ajouté en: v0.5.9
noDelay
boolean
Once a socket is assigned to this request and is connected
socket.setNoDelay()
will be called.
M request.setSocketKeepAlive([enable][, initialDelay])
Ajouté en: v0.5.9
Once a socket is assigned to this request and is connected
socket.setKeepAlive()
will be called.
M request.setTimeout(timeout[, callback])
Historique
Version | Changements |
---|---|
v9.0.0 | Consistently set socket timeout only when the socket connects. |
v0.5.9 | Ajouté en: v0.5.9 |
timeout
number
Milliseconds before a request times out.callback
Function
Optional function to be called when a timeout occurs. Same as binding to the'timeout'
event.- Returns:
http.ClientRequest
Once a socket is assigned to this request and is connected
socket.setTimeout()
will be called.
M request.socket
Ajouté en: v0.3.0
Reference to the underlying socket. Usually users will not want to access
this property. In particular, the socket will not emit 'readable'
events
because of how the protocol parser attaches to the socket.
JS
This property is guaranteed to be an instance of the net.Socket
class,
a subclass of stream.Duplex
, unless the user specified a socket
type other than net.Socket
.
M request.uncork()
Ajouté en: v13.2.0, v12.16.0
See writable.uncork()
.
M request.writableEnded
Ajouté en: v12.9.0
Is true
after request.end()
has been called. This property
does not indicate whether the data has been flushed, for this use
request.writableFinished
instead.
M request.writableFinished
Ajouté en: v12.7.0
Is true
if all data has been flushed to the underlying system, immediately
before the 'finish'
event is emitted.
M request.write(chunk[, encoding][, callback])
Ajouté en: v0.1.29
Sends a chunk of the body. This method can be called multiple times. If no
Content-Length
is set, data will automatically be encoded in HTTP Chunked
transfer encoding, so that server knows when the data ends. The
Transfer-Encoding: chunked
header is added. Calling request.end()
is necessary to finish sending the request.
The encoding
argument is optional and only applies when chunk
is a string.
Defaults to 'utf8'
.
The callback
argument is optional and will be called when this chunk of data
is flushed, but only if the chunk is non-empty.
Returns true
if the entire data was flushed successfully to the kernel
buffer. Returns false
if all or part of the data was queued in user memory.
'drain'
will be emitted when the buffer is free again.
When write
function is called with empty string or buffer, it does
nothing and waits for more input.
C http.Server
Ajouté en: v0.1.17
- Extends:
net.Server
E 'checkContinue'
Ajouté en: v0.3.0
request
http.IncomingMessage
response
http.ServerResponse
Emitted each time a request with an HTTP Expect: 100-continue
is received.
If this event is not listened for, the server will automatically respond
with a 100 Continue
as appropriate.
Handling this event involves calling response.writeContinue()
if the
client should continue to send the request body, or generating an appropriate
HTTP response (e.g. 400 Bad Request) if the client should not continue to send
the request body.
When this event is emitted and handled, the 'request'
event will
not be emitted.
E 'checkExpectation'
Ajouté en: v5.5.0
request
http.IncomingMessage
response
http.ServerResponse
Emitted each time a request with an HTTP Expect
header is received, where the
value is not 100-continue
. If this event is not listened for, the server will
automatically respond with a 417 Expectation Failed
as appropriate.
When this event is emitted and handled, the 'request'
event will
not be emitted.
E 'clientError'
Historique
Version | Changements |
---|---|
v12.0.0 | The default behavior will return a 431 Request Header Fields Too Large if a HPE_HEADER_OVERFLOW error occurs. |
v9.4.0 | The `rawPacket` is the current buffer that just parsed. Adding this buffer to the error object of `'clientError'` event is to make it possible that developers can log the broken packet. |
v6.0.0 | The default action of calling `.destroy()` on the `socket` will no longer take place if there are listeners attached for `'clientError'`. |
v0.1.94 | Ajouté en: v0.1.94 |
exception
Error
socket
stream.Duplex
If a client connection emits an 'error'
event, it will be forwarded here.
Listener of this event is responsible for closing/destroying the underlying
socket. For example, one may wish to more gracefully close the socket with a
custom HTTP response instead of abruptly severing the connection.
This event is guaranteed to be passed an instance of the net.Socket
class,
a subclass of stream.Duplex
, unless the user specifies a socket
type other than net.Socket
.
Default behavior is to try close the socket with a HTTP '400 Bad Request',
or a HTTP '431 Request Header Fields Too Large' in the case of a
HPE_HEADER_OVERFLOW
error. If the socket is not writable or headers
of the current attached http.ServerResponse
has been sent, it is
immediately destroyed.
socket
is the net.Socket
object that the error originated from.
JS
When the 'clientError'
event occurs, there is no request
or response
object, so any HTTP response sent, including response headers and payload,
must be written directly to the socket
object. Care must be taken to
ensure the response is a properly formatted HTTP response message.
err
is an instance of Error
with two extra columns:
bytesParsed
: the bytes count of request packet that Node.js may have parsed correctly;rawPacket
: the raw packet of current request.
In some cases, the client has already received the response and/or the socket
has already been destroyed, like in case of ECONNRESET
errors. Before
trying to send data to the socket, it is better to check that it is still
writable.
JS
E 'close'
Ajouté en: v0.1.4
Emitted when the server closes.
E 'connect'
Ajouté en: v0.7.0
request
http.IncomingMessage
Arguments for the HTTP request, as it is in the'request'
eventsocket
stream.Duplex
Network socket between the server and clienthead
Buffer
The first packet of the tunneling stream (may be empty)
Emitted each time a client requests an HTTP CONNECT
method. If this event is
not listened for, then clients requesting a CONNECT
method will have their
connections closed.
This event is guaranteed to be passed an instance of the net.Socket
class,
a subclass of stream.Duplex
, unless the user specifies a socket
type other than net.Socket
.
After this event is emitted, the request's socket will not have a 'data'
event listener, meaning it will need to be bound in order to handle data
sent to the server on that socket.
E 'connection'
Ajouté en: v0.1.0
socket
stream.Duplex
This event is emitted when a new TCP stream is established. socket
is
typically an object of type net.Socket
. Usually users will not want to
access this event. In particular, the socket will not emit 'readable'
events
because of how the protocol parser attaches to the socket. The socket
can
also be accessed at request.socket
.
This event can also be explicitly emitted by users to inject connections
into the HTTP server. In that case, any Duplex
stream can be passed.
If socket.setTimeout()
is called here, the timeout will be replaced with
server.keepAliveTimeout
when the socket has served a request (if
server.keepAliveTimeout
is non-zero).
This event is guaranteed to be passed an instance of the net.Socket
class,
a subclass of stream.Duplex
, unless the user specifies a socket
type other than net.Socket
.
E 'dropRequest'
Ajouté en: v18.7.0
request
http.IncomingMessage
Arguments for the HTTP request, as it is in the'request'
eventsocket
stream.Duplex
Network socket between the server and client
When the number of requests on a socket reaches the threshold of
server.maxRequestsPerSocket
, the server will drop new requests
and emit 'dropRequest'
event instead, then send 503
to client.
E 'request'
Ajouté en: v0.1.0
request
http.IncomingMessage
response
http.ServerResponse
Emitted each time there is a request. There may be multiple requests per connection (in the case of HTTP Keep-Alive connections).
E 'upgrade'
Historique
Version | Changements |
---|---|
v10.0.0 | Not listening to this event no longer causes the socket to be destroyed if a client sends an Upgrade header. |
v0.1.94 | Ajouté en: v0.1.94 |
request
http.IncomingMessage
Arguments for the HTTP request, as it is in the'request'
eventsocket
stream.Duplex
Network socket between the server and clienthead
Buffer
The first packet of the upgraded stream (may be empty)
Emitted each time a client requests an HTTP upgrade. Listening to this event is optional and clients cannot insist on a protocol change.
After this event is emitted, the request's socket will not have a 'data'
event listener, meaning it will need to be bound in order to handle data
sent to the server on that socket.
This event is guaranteed to be passed an instance of the net.Socket
class,
a subclass of stream.Duplex
, unless the user specifies a socket
type other than net.Socket
.
M server.close([callback])
Ajouté en: v0.1.90
callback
Function
Stops the server from accepting new connections. See net.Server.close()
.
M server.closeAllConnections()
Ajouté en: v18.2.0
Closes all connections connected to this server.
M server.closeIdleConnections()
Ajouté en: v18.2.0
Closes all connections connected to this server which are not sending a request or waiting for a response.
M server.headersTimeout
Ajouté en: v11.3.0, v10.14.0
number
Default:60000
Limit the amount of time the parser will wait to receive the complete HTTP headers.
If the timeout expires, the server responds with status 408 without forwarding the request to the request listener and then closes the connection.
It must be set to a non-zero value (e.g. 120 seconds) to protect against potential Denial-of-Service attacks in case the server is deployed without a reverse proxy in front.
M server.listen()
Starts the HTTP server listening for connections.
This method is identical to server.listen()
from net.Server
.
M server.listening
Ajouté en: v5.7.0
boolean
Indicates whether or not the server is listening for connections.
M server.maxHeadersCount
Ajouté en: v0.7.0
number
Default:2000
Limits maximum incoming headers count. If set to 0, no limit will be applied.
M server.requestTimeout
Historique
Version | Changements |
---|---|
v18.0.0 | The default request timeout changed from no timeout to 300s (5 minutes). |
v14.11.0 | Ajouté en: v14.11.0 |
number
Default:300000
Sets the timeout value in milliseconds for receiving the entire request from the client.
If the timeout expires, the server responds with status 408 without forwarding the request to the request listener and then closes the connection.
It must be set to a non-zero value (e.g. 120 seconds) to protect against potential Denial-of-Service attacks in case the server is deployed without a reverse proxy in front.
M server.setTimeout([msecs][, callback])
Historique
Version | Changements |
---|---|
v13.0.0 | The default timeout changed from 120s to 0 (no timeout). |
v0.9.12 | Ajouté en: v0.9.12 |
msecs
number
Default: 0 (no timeout)callback
Function
- Returns:
http.Server
Sets the timeout value for sockets, and emits a 'timeout'
event on
the Server object, passing the socket as an argument, if a timeout
occurs.
If there is a 'timeout'
event listener on the Server object, then it
will be called with the timed-out socket as an argument.
By default, the Server does not timeout sockets. However, if a callback
is assigned to the Server's 'timeout'
event, timeouts must be handled
explicitly.
M server.maxRequestsPerSocket
Ajouté en: v16.10.0
number
Requests per socket. Default: 0 (no limit)
The maximum number of requests socket can handle before closing keep alive connection.
A value of 0
will disable the limit.
When the limit is reached it will set the Connection
header value to close
,
but will not actually close the connection, subsequent requests sent
after the limit is reached will get 503 Service Unavailable
as a response.
M server.timeout
Historique
Version | Changements |
---|---|
v13.0.0 | The default timeout changed from 120s to 0 (no timeout). |
v0.9.12 | Ajouté en: v0.9.12 |
number
Timeout in milliseconds. Default: 0 (no timeout)
The number of milliseconds of inactivity before a socket is presumed to have timed out.
A value of 0
will disable the timeout behavior on incoming connections.
The socket timeout logic is set up on connection, so changing this value only affects new connections to the server, not any existing connections.
M server.keepAliveTimeout
Ajouté en: v8.0.0
number
Timeout in milliseconds. Default:5000
(5 seconds).
The number of milliseconds of inactivity a server needs to wait for additional
incoming data, after it has finished writing the last response, before a socket
will be destroyed. If the server receives new data before the keep-alive
timeout has fired, it will reset the regular inactivity timeout, i.e.,
server.timeout
.
A value of 0
will disable the keep-alive timeout behavior on incoming
connections.
A value of 0
makes the http server behave similarly to Node.js versions prior
to 8.0.0, which did not have a keep-alive timeout.
The socket timeout logic is set up on connection, so changing this value only affects new connections to the server, not any existing connections.
C http.ServerResponse
Ajouté en: v0.1.17
- Extends:
http.OutgoingMessage
This object is created internally by an HTTP server, not by the user. It is
passed as the second parameter to the 'request'
event.
E 'close'
Ajouté en: v0.6.7
Indicates that the response is completed, or its underlying connection was terminated prematurely (before the response completion).
E 'finish'
Ajouté en: v0.3.6
Emitted when the response has been sent. More specifically, this event is emitted when the last segment of the response headers and body have been handed off to the operating system for transmission over the network. It does not imply that the client has received anything yet.
M response.addTrailers(headers)
Ajouté en: v0.3.0
headers
Object
This method adds HTTP trailing headers (a header but at the end of the message) to the response.
Trailers will only be emitted if chunked encoding is used for the response; if it is not (e.g. if the request was HTTP/1.0), they will be silently discarded.
HTTP requires the Trailer
header to be sent in order to
emit trailers, with a list of the header fields in its value. E.g.,
JS
Attempting to set a header field name or value that contains invalid characters
will result in a TypeError
being thrown.
M response.connection
Déprécié en: v13.0.0
See response.socket
.
M response.cork()
Ajouté en: v13.2.0, v12.16.0
See writable.cork()
.
M response.end([data[, encoding]][, callback])
Historique
Version | Changements |
---|---|
v10.0.0 | This method now returns a reference to `ServerResponse`. |
v0.1.90 | Ajouté en: v0.1.90 |
This method signals to the server that all of the response headers and body
have 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 similar in effect to calling
response.write(data, encoding)
followed by response.end(callback)
.
If callback
is specified, it will be called when the response stream
is finished.
M response.finished
Déprécié en: v13.4.0, v12.16.0
The response.finished
property will be true
if response.end()
has been called.
M response.flushHeaders()
Ajouté en: v1.6.0
Flushes the response headers. See also: request.flushHeaders()
.
M response.getHeader(name)
Ajouté en: v0.4.0
Reads out a header that's already been queued but not sent to the client.
The name is case-insensitive. The type of the return value depends
on the arguments provided to response.setHeader()
.
JS
M response.getHeaderNames()
Ajouté en: v7.7.0
- Returns: string[]
Returns an array containing the unique names of the current outgoing headers. All header names are lowercase.
JS
M response.getHeaders()
Ajouté en: v7.7.0
- Returns:
Object
Returns a shallow copy of the current outgoing headers. Since a shallow copy is used, array values may be mutated without additional calls to various header-related http module methods. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase.
The object returned by the response.getHeaders()
method does not
prototypically inherit from the JavaScript Object
. This means that typical
Object
methods such as obj.toString()
, obj.hasOwnProperty()
, and others
are not defined and will not work.
JS
M response.hasHeader(name)
Ajouté en: v7.7.0
Returns true
if the header identified by name
is currently set in the
outgoing headers. The header name matching is case-insensitive.
JS
M response.headersSent
Ajouté en: v0.9.3
Boolean (read-only). True if headers were sent, false otherwise.
M response.removeHeader(name)
Ajouté en: v0.4.0
name
string
Removes a header that's queued for implicit sending.
JS
M response.req
Ajouté en: v15.7.0
A reference to the original HTTP request
object.
M response.sendDate
Ajouté en: v0.7.5
When true, the Date header will be automatically generated and sent in the response if it is not already present in the headers. Defaults to true.
This should only be disabled for testing; HTTP requires the Date header in responses.
M response.setHeader(name, value)
Ajouté en: v0.4.0
name
string
value
any
- Returns:
http.ServerResponse
Returns the response object.
Sets a single header value for implicit headers. If this header already exists
in the to-be-sent headers, its value will be replaced. Use an array of strings
here to send multiple headers with the same name. Non-string values will be
stored without modification. Therefore, response.getHeader()
may return
non-string values. However, the non-string values will be converted to strings
for network transmission. The same response object is returned to the caller,
to enable call chaining.
JS
or
JS
Attempting to set a header field name or value that contains invalid characters
will result in a TypeError
being thrown.
When headers have been set with response.setHeader()
, they will be merged
with any headers passed to response.writeHead()
, with the headers passed
to response.writeHead()
given precedence.
JS
If response.writeHead()
method is called and this method has not been
called, it will directly write the supplied header values onto the network
channel without caching internally, and the response.getHeader()
on the
header will not yield the expected result. If progressive population of headers
is desired with potential future retrieval and modification, use
response.setHeader()
instead of response.writeHead()
.
M response.setTimeout(msecs[, callback])
Ajouté en: v0.9.12
msecs
number
callback
Function
- Returns:
http.ServerResponse
Sets the Socket's timeout value to msecs
. If a callback is
provided, then it is added as a listener on the 'timeout'
event on
the response object.
If no 'timeout'
listener is added to the request, the response, or
the server, then sockets are destroyed when they time out. If a handler is
assigned to the request, the response, or the server's 'timeout'
events,
timed out sockets must be handled explicitly.
M response.socket
Ajouté en: v0.3.0
Reference to the underlying socket. Usually users will not want to access
this property. In particular, the socket will not emit 'readable'
events
because of how the protocol parser attaches to the socket. After
response.end()
, the property is nulled.
JS
This property is guaranteed to be an instance of the net.Socket
class,
a subclass of stream.Duplex
, unless the user specified a socket
type other than net.Socket
.
M response.statusCode
Ajouté en: v0.4.0
number
Default:200
When using implicit headers (not calling response.writeHead()
explicitly),
this property controls the status code that will be sent to the client when
the headers get flushed.
JS
After response header was sent to the client, this property indicates the status code which was sent out.
M response.statusMessage
Ajouté en: v0.11.8
When using implicit headers (not calling response.writeHead()
explicitly),
this property controls the status message that will be sent to the client when
the headers get flushed. If this is left as undefined
then the standard
message for the status code will be used.
JS
After response header was sent to the client, this property indicates the status message which was sent out.
M response.uncork()
Ajouté en: v13.2.0, v12.16.0
See writable.uncork()
.
M response.writableEnded
Ajouté en: v12.9.0
Is true
after response.end()
has been called. This property
does not indicate whether the data has been flushed, for this use
response.writableFinished
instead.
M response.writableFinished
Ajouté en: v12.7.0
Is true
if all data has been flushed to the underlying system, immediately
before the 'finish'
event is emitted.
M response.write(chunk[, encoding][, callback])
Ajout é en: v0.1.29
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 may be called multiple times to provide successive parts of the body.
In the node:http
module, the response body is omitted when the
request is a HEAD request. Similarly, the 204
and 304
responses
must 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.
callback
will be called when this chunk of data is flushed.
This is the raw HTTP body and has nothing to do with higher-level multi-part body encodings that may be used.
The first time response.write()
is called, it will send the buffered
header information and the first chunk of the body to the client. The second
time 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 the
first chunk of the body.
Returns true
if the entire data was flushed successfully to the kernel
buffer. Returns false
if all or part of the data was queued in user memory.
'drain'
will be emitted when the buffer is free again.
M response.writeContinue()
Ajouté en: v0.3.0
Sends an HTTP/1.1 100 Continue message to the client, indicating that
the request body should be sent. See the 'checkContinue'
event on
Server
.
M response.writeEarlyHints(hints[, callback])
Historique
Version | Changements |
---|---|
v18.11.0 | Allow passing hints as an object. |
v18.11.0 | Ajouté en: v18.11.0 |
Sends an HTTP/1.1 103 Early Hints message to the client with a Link header,
indicating that the user agent can preload/preconnect the linked resources.
The hints
is an object containing the values of headers to be sent with
early hints message. The optional callback
argument will be called when
the response message has been written.
Example
JS
M response.writeHead(statusCode[, statusMessage][, headers])
Historique
Version | Changements |
---|---|
v14.14.0 | Allow passing headers as an array. |
v11.10.0, v10.17.0 | Return `this` from `writeHead()` to allow chaining with `end()`. |
v5.11.0, v4.4.5 | A `RangeError` is thrown if `statusCode` is not a number in the range `[100, 999]`. |
v0.1.30 | Ajouté en: v0.1.30 |
statusCode
number
statusMessage
string
headers
Object
|Array
- Returns:
http.ServerResponse
Sends a response header to the request. The status code is a 3-digit HTTP
status code, like 404
. The last argument, headers
, are the response headers.
Optionally one can give a human-readable statusMessage
as the second
argument.
headers
may be an Array
where the keys and values are in the same list.
It is not a list of tuples. So, the even-numbered offsets are key values,
and the odd-numbered offsets are the associated values. The array is in the same
format as request.rawHeaders
.
Returns a reference to the ServerResponse
, so that calls can be chained.
JS
This method must only be called once on a message and it must
be called before response.end()
is called.
If response.write()
or response.end()
are called before calling
this, the implicit/mutable headers will be calculated and call this function.
When headers have been set with response.setHeader()
, they will be merged
with any headers passed to response.writeHead()
, with the headers passed
to response.writeHead()
given precedence.
If this method is called and response.setHeader()
has not been called,
it will directly write the supplied header values onto the network channel
without caching internally, and the response.getHeader()
on the header
will not yield the expected result. If progressive population of headers is
desired with potential future retrieval and modification, use
response.setHeader()
instead.
JS
Content-Length
is read in bytes, not characters. Use
Buffer.byteLength()
to determine the length of the body in bytes. Node.js
will check whether Content-Length
and the length of the body which has
been transmitted are equal or not.
Attempting to set a header field name or value that contains invalid characters
will result in a [Error
][] being thrown.
M response.writeProcessing()
Ajouté en: v10.0.0
Sends a HTTP/1.1 102 Processing message to the client, indicating that the request body should be sent.
C http.IncomingMessage
Historique
Version | Changements |
---|---|
v15.5.0 | The `destroyed` value returns `true` after the incoming data is consumed. |
v13.1.0, v12.16.0 | The `readableHighWaterMark` value mirrors that of the socket. |
v0.1.17 | Ajouté en: v0.1.17 |
- Extends:
stream.Readable
An IncomingMessage
object is created by http.Server
or
http.ClientRequest
and passed as the first argument to the 'request'
and 'response'
event respectively. It may be used to access response
status, headers, and data.
Different from its socket
value which is a subclass of stream.Duplex
, the
IncomingMessage
itself extends stream.Readable
and is created separately to
parse and emit the incoming HTTP headers and payload, as the underlying socket
may be reused multiple times in case of keep-alive.
E 'aborted'
Déprécié en: v17.0.0, v16.12.0
Emitted when the request has been aborted.
E 'close'
Historique
Version | Changements |
---|---|
v16.0.0 | The close event is now emitted when the request has been completed and not when the underlying socket is closed. |
v0.4.2 | Ajouté en: v0.4.2 |
Emitted when the request has been completed.
M message.aborted
Déprécié en: v17.0.0, v16.12.0
The message.aborted
property will be true
if the request has
been aborted.
M message.complete
Ajouté en: v0.3.0
The message.complete
property will be true
if a complete HTTP message has
been received and successfully parsed.
This property is particularly useful as a means of determining if a client or server fully transmitted a message before a connection was terminated:
JS
M message.connection
Déprécié en: v16.0.0
Alias for message.socket
.
M message.destroy([error])
Historique
Version | Changements |
---|---|
v14.5.0, v12.19.0 | The function returns `this` for consistency with other Readable streams. |
v0.3.0 | Ajouté en: v0.3.0 |
Calls destroy()
on the socket that received the IncomingMessage
. If error
is provided, an 'error'
event is emitted on the socket and error
is passed
as an argument to any listeners on the event.
M message.headers
Historique
Version | Changements |
---|---|
v15.1.0 | `message.headers` is now lazily computed using an accessor property on the prototype and is no longer enumerable. |
v0.1.5 | Ajouté en: v0.1.5 |
The request/response headers object.
Key-value pairs of header names and values. Header names are lower-cased.
JS
Duplicates in raw headers are handled in the following ways, depending on the header name:
- Duplicates of
age
,authorization
,content-length
,content-type
,etag
,expires
,from
,host
,if-modified-since
,if-unmodified-since
,last-modified
,location
,max-forwards
,proxy-authorization
,referer
,retry-after
,server
, oruser-agent
are discarded. set-cookie
is always an array. Duplicates are added to the array.- For duplicate
cookie
headers, the values are joined together with;
. - For all other headers, the values are joined together with
,
.
M message.headersDistinct
Ajouté en: v18.3.0
Similar to message.headers
, but there is no join logic and the values are
always arrays of strings, even for headers received just once.
JS
M message.httpVersion
Ajouté en: v0.1.1
In case of server request, the HTTP version sent by the client. In the case of
client response, the HTTP version of the connected-to server.
Probably either '1.1'
or '1.0'
.
Also message.httpVersionMajor
is the first integer and
message.httpVersionMinor
is the second.
M message.method
Ajouté en: v0.1.1
Only valid for request obtained from http.Server
.
The request method as a string. Read only. Examples: 'GET'
, 'DELETE'
.
M message.rawHeaders
Ajouté en: v0.11.6
- string[]
The raw request/response headers list exactly as they were received.
The keys and values are in the same list. It is not a list of tuples. So, the even-numbered offsets are key values, and the odd-numbered offsets are the associated values.
Header names are not lowercased, and duplicates are not merged.
JS
M message.rawTrailers
Ajouté en: v0.11.6
- string[]
The raw request/response trailer keys and values exactly as they were
received. Only populated at the 'end'
event.
M message.setTimeout(msecs[, callback])
Ajouté en: v0.5.9
msecs
number
callback
Function
- Returns:
http.IncomingMessage
Calls message.socket.setTimeout(msecs, callback)
.
M message.socket
Ajouté en: v0.3.0
The net.Socket
object associated with the connection.
With HTTPS support, use request.socket.getPeerCertificate()
to obtain the
client's authentication details.
This property is guaranteed to be an instance of the net.Socket
class,
a subclass of stream.Duplex
, unless the user specified a socket
type other than net.Socket
or internally nulled.
M message.statusCode
Ajouté en: v0.1.1
Only valid for response obtained from http.ClientRequest
.
The 3-digit HTTP response status code. E.G. 404
.
M message.statusMessage
Ajouté en: v0.11.10
Only valid for response obtained from http.ClientRequest
.
The HTTP response status message (reason phrase). E.G. OK
or Internal Server
Error
.
M message.trailers
Ajouté en: v0.3.0
The request/response trailers object. Only populated at the 'end'
event.
M message.trailersDistinct
Ajouté en: v18.3.0
Similar to message.trailers
, but there is no join logic and the values are
always arrays of strings, even for headers received just once.
Only populated at the 'end'
event.
M message.url
Ajouté en: v0.1.90
Only valid for request obtained from http.Server
.
Request URL string. This contains only the URL that is present in the actual HTTP request. Take the following request:
HTTP
To parse the URL into its parts:
JS
When request.url
is '/status?name=ryan'
and request.headers.host
is
'localhost:3000'
:
BASH
C http.OutgoingMessage
Ajouté en: v0.1.17
- Extends:
Stream
This class serves as the parent class of http.ClientRequest
and http.ServerResponse
. It is an abstract outgoing message from
the perspective of the participants of an HTTP transaction.
E 'drain'
Ajouté en: v0.3.6
Emitted when the buffer of the message is free again.
E 'finish'
Ajouté en: v0.1.17
Emitted when the transmission is finished successfully.
E 'prefinish'
Ajouté en: v0.11.6
Emitted after outgoingMessage.end()
is called.
When the event is emitted, all data has been processed but not necessarily
completely flushed.
M outgoingMessage.addTrailers(headers)
Ajouté en: v0.3.0
headers
Object
Adds HTTP trailers (headers but at the end of the message) to the message.
Trailers will only be emitted if the message is chunked encoded. If not, the trailers will be silently discarded.
HTTP requires the Trailer
header to be sent to emit trailers,
with a list of header field names in its value, e.g.
JS
Attempting to set a header field name or value that contains invalid characters
will result in a TypeError
being thrown.
M outgoingMessage.appendHeader(name, value)
Ajouté en: v18.3.0
Append a single header value for the header object.
If the value is an array, this is equivalent of calling this method multiple times.
If there were no previous value for the header, this is equivalent of calling
outgoingMessage.setHeader(name, value)
.
Depending of the value of options.uniqueHeaders
when the client request or the
server were created, this will end up in the header being sent multiple times or
a single time with values joined using ;
.
M outgoingMessage.connection
Déprécié en: v15.12.0, v14.17.1
Alias of outgoingMessage.socket
.
M outgoingMessage.cork()
Ajouté en: v13.2.0, v12.16.0
See writable.cork()
.
M outgoingMessage.destroy([error])
Ajouté en: v0.3.0
Destroys the message. Once a socket is associated with the message and is connected, that socket will be destroyed as well.
M outgoingMessage.end(chunk[, encoding][, callback])
Historique
Version | Changements |
---|---|
v0.11.6 | add `callback` argument. |
v0.1.90 | Ajouté en: v0.1.90 |
Finishes the outgoing message. If any parts of the body are unsent, it will
flush them to the underlying system. If the message is chunked, it will
send the terminating chunk 0\r\n\r\n
, and send the trailers (if any).
If chunk
is specified, it is equivalent to calling
outgoingMessage.write(chunk, encoding)
, followed by
outgoingMessage.end(callback)
.
If callback
is provided, it will be called when the message is finished
(equivalent to a listener of the 'finish'
event).
M outgoingMessage.flushHeaders()
Ajouté en: v1.6.0
Flushes the message headers.
For efficiency reason, Node.js normally buffers the message headers
until outgoingMessage.end()
is called or the first chunk of message data
is written. It then tries to pack the headers and data into a single TCP
packet.
It is usually desired (it saves a TCP round-trip), but not when the first
data is not sent until possibly much later. outgoingMessage.flushHeaders()
bypasses the optimization and kickstarts the message.
M outgoingMessage.getHeader(name)
Ajouté en: v0.4.0
Gets the value of the HTTP header with the given name. If that header is not
set, the returned value will be undefined
.
M outgoingMessage.getHeaderNames()
Ajouté en: v7.7.0
- Returns string[]
Returns an array containing the unique names of the current outgoing headers. All names are lowercase.
M outgoingMessage.getHeaders()
Ajouté en: v7.7.0
- Returns:
Object
Returns a shallow copy of the current outgoing headers. Since a shallow copy is used, array values may be mutated without additional calls to various header-related HTTP module methods. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase.
The object returned by the outgoingMessage.getHeaders()
method does
not prototypically inherit from the JavaScript Object
. This means that
typical Object
methods such as obj.toString()
, obj.hasOwnProperty()
,
and others are not defined and will not work.
JS
M outgoingMessage.hasHeader(name)
Ajouté en: v7.7.0
Returns true
if the header identified by name
is currently set in the
outgoing headers. The header name is case-insensitive.
JS
M outgoingMessage.headersSent
Ajouté en: v0.9.3
Read-only. true
if the headers were sent, otherwise false
.
M outgoingMessage.pipe()
Ajouté en: v9.0.0
Overrides the stream.pipe()
method inherited from the legacy Stream
class
which is the parent class of http.OutgoingMessage
.
Calling this method will throw an Error
because outgoingMessage
is a
write-only stream.
M outgoingMessage.removeHeader(name)
Ajouté en: v0.4.0
name
string
Header name
Removes a header that is queued for implicit sending.
JS
M outgoingMessage.setHeader(name, value)
Ajouté en: v0.4.0
Sets a single header value. If the header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings to send multiple headers with the same name.
M outgoingMessage.setTimeout(msesc[, callback])
Ajouté en: v0.9.12
msesc
number
callback
Function
Optional function to be called when a timeout occurs. Same as binding to thetimeout
event.- Returns:
this
Once a socket is associated with the message and is connected,
socket.setTimeout()
will be called with msecs
as the first parameter.
M outgoingMessage.socket
Ajouté en: v0.3.0
Reference to the underlying socket. Usually, users will not want to access this property.
After calling outgoingMessage.end()
, this property will be nulled.
M outgoingMessage.uncork()
Ajouté en: v13.2.0, v12.16.0
M outgoingMessage.writableCorked
Ajouté en: v13.2.0, v12.16.0
The number of times outgoingMessage.cork()
has been called.
M outgoingMessage.writableEnded
Ajouté en: v12.9.0
Is true
if outgoingMessage.end()
has been called. This property does
not indicate whether the data has been flushed. For that purpose, use
message.writableFinished
instead.
M outgoingMessage.writableFinished
Ajouté en: v12.7.0
Is true
if all data has been flushed to the underlying system.
M outgoingMessage.writableHighWaterMark
Ajouté en: v12.9.0
The highWaterMark
of the underlying socket if assigned. Otherwise, the default
buffer level when writable.write()
starts returning false (16384
).
M outgoingMessage.writableLength
Ajouté en: v12.9.0
The number of buffered bytes.
M outgoingMessage.writableObjectMode
Ajouté en: v12.9.0
Always false
.
M outgoingMessage.write(chunk[, encoding][, callback])
Historique
Version | Changements |
---|---|
v0.11.6 | The `callback` argument was added. |
v0.1.29 | Ajouté en: v0.1.29 |
Sends a chunk of the body. This method can be called multiple times.
The encoding
argument is only relevant when chunk
is a string. Defaults to
'utf8'
.
The callback
argument is optional and will be called when this chunk of data
is flushed.
Returns true
if the entire data was flushed successfully to the kernel
buffer. Returns false
if all or part of the data was queued in the user
memory. The 'drain'
event will be emitted when the buffer is free again.
M http.METHODS
Ajouté en: v0.11.8
- string[]
A list of the HTTP methods that are supported by the parser.
M http.STATUS_CODES
Ajouté en: v0.1.22
A collection of all the standard HTTP response status codes, and the
short description of each. For example, http.STATUS_CODES[404] === 'Not
Found'
.
M http.createServer([options][, requestListener])
Historique
Version | Changements |
---|---|
v18.0.0 | The `requestTimeout`, `headersTimeout`, `keepAliveTimeout`, and `connectionsCheckingInterval` options are supported now. |
v18.0.0 | The `noDelay` option now defaults to `true`. |
v17.7.0 | The `noDelay`, `keepAlive` and `keepAliveInitialDelay` options are supported now. |
v13.8.0, v12.15.0, v10.19.0 | The `insecureHTTPParser` option is supported now. |
v13.3.0 | The `maxHeaderSize` option is supported now. |
v9.6.0, v8.12.0 | The `options` argument is supported now. |
v0.1.13 | Ajouté en: v0.1.13 |
options
Object
IncomingMessage
http.IncomingMessage
Specifies theIncomingMessage
class to be used. Useful for extending the originalIncomingMessage
. Default:IncomingMessage
.ServerResponse
http.ServerResponse
Specifies theServerResponse
class to be used. Useful for extending the originalServerResponse
. Default:ServerResponse
.requestTimeout
: Sets the timeout value in milliseconds for receiving the entire request from the client. Seeserver.requestTimeout
for more information. Default:300000
.headersTimeout
: Sets the timeout value in milliseconds for receiving the complete HTTP headers from the client. Seeserver.headersTimeout
for more information. Default:60000
.keepAliveTimeout
: The number of milliseconds of inactivity a server needs to wait for additional incoming data, after it has finished writing the last response, before a socket will be destroyed. Seeserver.keepAliveTimeout
for more information. Default:5000
.connectionsCheckingInterval
: Sets the interval value in milliseconds to check for request and headers timeout in incomplete requests. Default:30000
.insecureHTTPParser
boolean
Use an insecure HTTP parser that accepts invalid HTTP headers whentrue
. Using the insecure parser should be avoided. See--insecure-http-parser
for more information. Default:false
maxHeaderSize
number
Optionally overrides the value of--max-http-header-size
for requests received by this server, i.e. the maximum length of request headers in bytes. Default: 16384 (16 KiB).noDelay
boolean
If set totrue
, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. Default:true
.keepAlive
boolean
If set totrue
, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, similarly on what is done in [socket.setKeepAlive([enable][, initialDelay])
][socket.setKeepAlive(enable, initialDelay)
]. Default:false
.keepAliveInitialDelay
number
If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. Default:0
.uniqueHeaders
Array
A list of response headers that should be sent only once. If the header's value is an array, the items will be joined using;
.
requestListener
Function
Returns:
http.Server
Returns a new instance of http.Server
.
The requestListener
is a function which is automatically
added to the 'request'
event.
CJS
CJS
M http.get(options[, callback])
M http.get(url[, options][, callback])
Historique
Version | Changements |
---|---|
v10.9.0 | The `url` parameter can now be passed along with a separate `options` object. |
v7.5.0 | The `options` parameter can be a WHATWG `URL` object. |
v0.3.6 | Ajouté en: v0.3.6 |
url
string
|URL
options
Object
Accepts the sameoptions
ashttp.request()
, with themethod
always set toGET
. Properties that are inherited from the prototype are ignored.callback
Function
- Returns:
http.ClientRequest
Since most requests are GET requests without bodies, Node.js provides this
convenience method. The only difference between this method and
http.request()
is that it sets the method to GET and calls req.end()
automatically. The callback must take care to consume the response
data for reasons stated in http.ClientRequest
section.
The callback
is invoked with a single argument that is an instance of
http.IncomingMessage
.
JSON fetching example:
JS
M http.globalAgent
Ajouté en: v0.5.9
Global instance of Agent
which is used as the default for all HTTP client
requests.
M http.maxHeaderSize
Ajouté en: v11.6.0, v10.15.0
Read-only property specifying the maximum allowed size of HTTP headers in bytes.
Defaults to 16 KiB. Configurable using the --max-http-header-size
CLI
option.
This can be overridden for servers and client requests by passing the
maxHeaderSize
option.
M http.request(options[, callback])
M http.request(url[, options][, callback])
Historique
Version | Changements |
---|---|
v16.7.0, v14.18.0 | When using a `URL` object parsed username and password will now be properly URI decoded. |
v15.3.0, v14.17.0 | It is possible to abort a request with an AbortSignal. |
v13.8.0, v12.15.0, v10.19.0 | The `insecureHTTPParser` option is supported now. |
v13.3.0 | The `maxHeaderSize` option is supported now. |
v10.9.0 | The `url` parameter can now be passed along with a separate `options` object. |
v7.5.0 | The `options` parameter can be a WHATWG `URL` object. |
v0.3.6 | Ajouté en: v0.3.6 |
url
string
|URL
options
Object
agent
http.Agent
|boolean
ControlsAgent
behavior. Possible values:undefined
(default): usehttp.globalAgent
for this host and port.Agent
object: explicitly use the passed inAgent
.false
: causes a newAgent
with default values to be used.
auth
string
Basic authentication ('user:password'
) to compute an Authorization header.createConnection
Function
A function that produces a socket/stream to use for the request when theagent
option is not used. This can be used to avoid creating a customAgent
class just to override the defaultcreateConnection
function. Seeagent.createConnection()
for more details. AnyDuplex
stream is a valid return value.defaultPort
number
Default port for the protocol. Default:agent.defaultPort
if anAgent
is used, elseundefined
.family
number
IP address family to use when resolvinghost
orhostname
. Valid values are4
or6
. When unspecified, both IP v4 and v6 will be used.headers
Object
An object containing request headers.hints
number
Optionaldns.lookup()
hints.host
string
A domain name or IP address of the server to issue the request to. Default:'localhost'
.hostname
string
Alias forhost
. To supporturl.parse()
,hostname
will be used if bothhost
andhostname
are specified.insecureHTTPParser
boolean
Use an insecure HTTP parser that accepts invalid HTTP headers whentrue
. Using the insecure parser should be avoided. See--insecure-http-parser
for more information. Default:false
localAddress
string
Local interface to bind for network connections.localPort
number
Local port to connect from.lookup
Function
Custom lookup function. Default:dns.lookup()
.maxHeaderSize
number
Optionally overrides the value of--max-http-header-size
(the maximum length of response headers in bytes) for responses received from the server. Default: 16384 (16 KiB).method
string
A string specifying the HTTP request method. Default:'GET'
.path
string
Request path. Should include query string if any. E.G.'/index.html?page=12'
. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future. Default:'/'
.port
number
Port of remote server. Default:defaultPort
if set, else80
.protocol
string
Protocol to use. Default:'http:'
.setHost
boolean
: Specifies whether or not to automatically add theHost
header. Defaults totrue
.signal
AbortSignal
: An AbortSignal that may be used to abort an ongoing request.socketPath
string
Unix domain socket. Cannot be used if one ofhost
orport
is specified, as those specify a TCP Socket.timeout
number
: A number specifying the socket timeout in milliseconds. This will set the timeout before the socket is connected.uniqueHeaders
Array
A list of request headers that should be sent only once. If the header's value is an array, the items will be joined using;
.
callback
Function
- Returns:
http.ClientRequest
options
in socket.connect()
are also supported.
Node.js maintains several connections per server to make HTTP requests. This function allows one to transparently issue requests.
url
can be a string or a URL
object. If url
is a
string, it is automatically parsed with new URL()
. If it is a URL
object, it will be automatically converted to an ordinary options
object.
If both url
and options
are specified, the objects are merged, with the
options
properties taking precedence.
The optional callback
parameter will be added as a one-time listener for
the 'response'
event.
http.request()
returns an instance of the http.ClientRequest
class. The ClientRequest
instance is a writable stream. If one needs to
upload a file with a POST request, then write to the ClientRequest
object.
JS
In the example req.end()
was called. With http.request()
one
must always call req.end()
to signify the end of the request -
even if there is no data being written to the request body.
If any error is encountered during the request (be that with DNS resolution,
TCP level errors, or actual HTTP parse errors) an 'error'
event is emitted
on the returned request object. As with all 'error'
events, if no listeners
are registered the error will be thrown.
There are a few special headers that should be noted.
Sending a 'Connection: keep-alive' will notify Node.js that the connection to the server should be persisted until the next request.
Sending a 'Content-Length' header will disable the default chunked encoding.
Sending an 'Expect' header will immediately send the request headers. Usually, when sending 'Expect: 100-continue', both a timeout and a listener for the
'continue'
event should be set. See RFC 2616 Section 8.2.3 for more information.Sending an Authorization header will override using the
auth
option to compute basic authentication.
Example using a URL
as options
:
JS
In a successful request, the following events will be emitted in the following order:
'socket'
'response'
'data'
any number of times, on theres
object ('data'
will not be emitted at all if the response body is empty, for instance, in most redirects)'end'
on theres
object
'close'
In the case of a connection error, the following events will be emitted:
'socket'
'error'
'close'
In the case of a premature connection close before the response is received, the following events will be emitted in the following order:
'socket'
'error'
with an error with message'Error: socket hang up'
and code'ECONNRESET'
'close'
In the case of a premature connection close after the response is received, the following events will be emitted in the following order:
'socket'
'response'
'data'
any number of times, on theres
object
- (connection closed here)
'aborted'
on theres
object'error'
on theres
object with an error with message'Error: aborted'
and code'ECONNRESET'
.'close'
'close'
on theres
object
If req.destroy()
is called before a socket is assigned, the following
events will be emitted in the following order:
- (
req.destroy()
called here) 'error'
with an error with message'Error: socket hang up'
and code'ECONNRESET'
'close'
If req.destroy()
is called before the connection succeeds, the following
events will be emitted in the following order:
'socket'
- (
req.destroy()
called here) 'error'
with an error with message'Error: socket hang up'
and code'ECONNRESET'
'close'
If req.destroy()
is called after the response is received, the following
events will be emitted in the following order:
'socket'
'response'
'data'
any number of times, on theres
object
- (
req.destroy()
called here) 'aborted'
on theres
object'error'
on theres
object with an error with message'Error: aborted'
and code'ECONNRESET'
.'close'
'close'
on theres
object
If req.abort()
is called before a socket is assigned, the following
events will be emitted in the following order:
- (
req.abort()
called here) 'abort'
'close'
If req.abort()
is called before the connection succeeds, the following
events will be emitted in the following order:
'socket'
- (
req.abort()
called here) 'abort'
'error'
with an error with message'Error: socket hang up'
and code'ECONNRESET'
'close'
If req.abort()
is called after the response is received, the following
events will be emitted in the following order:
'socket'
'response'
'data'
any number of times, on theres
object
- (
req.abort()
called here) 'abort'
'aborted'
on theres
object'error'
on theres
object with an error with message'Error: aborted'
and code'ECONNRESET'
.'close'
'close'
on theres
object
Setting the timeout
option or using the setTimeout()
function will
not abort the request or do anything besides add a 'timeout'
event.
Passing an AbortSignal
and then calling abort
on the corresponding
AbortController
will behave the same way as calling .destroy()
on the
request itself.
M http.validateHeaderName(name)
Ajouté en: v14.3.0
name
string
Performs the low-level validations on the provided name
that are done when
res.setHeader(name, value)
is called.
Passing illegal value as name
will result in a TypeError
being thrown,
identified by code: 'ERR_INVALID_HTTP_TOKEN'
.
It is not necessary to use this method before passing headers to an HTTP request or response. The HTTP module will automatically validate such headers. Examples:
Example:
JS
M http.validateHeaderValue(name, value)
Ajouté en: v14.3.0
Performs the low-level validations on the provided value
that are done when
res.setHeader(name, value)
is called.
Passing illegal value as value
will result in a TypeError
being thrown.
- Undefined value error is identified by
code: 'ERR_HTTP_INVALID_HEADER_VALUE'
. - Invalid value character error is identified by
code: 'ERR_INVALID_CHAR'
.
It is not necessary to use this method before passing headers to an HTTP request or response. The HTTP module will automatically validate such headers.
Examples:
JS
M http.setMaxIdleHTTPParsers
Ajouté en: v18.8.0
Set the maximum number of idle HTTP parsers. Default: 1000
.