HTTP
目录
- 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.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.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
自 v0.10.0 版本开始新增
源代码: 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
自 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])
历史
版本 | 历史变更 |
---|---|
v15.6.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 | 自 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])
自 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)
自 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)
自 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()
自 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
历史
版本 | 历史变更 |
---|---|
v16.0.0 | The property now has a `null` prototype. |
v0.11.4 | 自 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])
历史
版本 | 历史变更 |
---|---|
v16.15.0 | The `options` parameter is now optional. |
v0.11.4 | 自 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
自 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
自 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
自 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
历史
版本 | 历史变更 |
---|---|
v16.0.0 | The property now has a `null` prototype. |
v0.5.9 | 自 v0.5.9 版本开始新增 |
An object which contains queues of requests that have not yet been assigned to sockets. Do not modify.
M agent.sockets
历史
版本 | 历史变更 |
---|---|
v16.0.0 | The property now has a `null` prototype. |
v0.3.6 | 自 v0.3.6 版本开始新增 |
An object which contains arrays of sockets currently in use by the agent. Do not modify.
C http.ClientRequest
自 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'
自 v16.12.0 版本开始弃用