HTTP#Stability: 2 - Stable
To use the HTTP server and client one must 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:
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 The raw headers as they were received are retained in the
Class:
|
Version | Changes |
---|---|
v11.0.0 | The |
v0.11.14 | Added in: v0.11.14 |
The request.aborted
property will be true
if the request has
been aborted.
request.connection
#request.socket
.See request.socket
.
request.end([data[, encoding]][, callback])
#Version | Changes |
---|---|
v10.0.0 | This method now returns a reference to |
v0.1.90 | Added in: v0.1.90 |
data
<string> | <Buffer>encoding
<string>callback
<Function>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.
request.destroy([error])
#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.
request.destroyed
#Is true
after request.destroy()
has been called.
See writable.destroyed
for further details.
request.finished
#request.writableEnded
.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()
.
request.flushHeaders()
#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.
request.getHeader(name)
#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()
.
request.setHeader('content-type', 'text/html');
request.setHeader('Content-Length', Buffer.byteLength(body));
request.setHeader('Cookie', ['type=ninja', 'language=javascript']);
const contentType = request.getHeader('Content-Type');
// 'contentType' is 'text/html'
const contentLength = request.getHeader('Content-Length');
// 'contentLength' is of type number
const cookie = request.getHeader('Cookie');
// 'cookie' is of type string[]
request.maxHeadersCount
#2000
Limits maximum response headers count. If set to 0, no limit will be applied.
request.path
#request.removeHeader(name)
#name
<string>Removes a header that's already defined into headers object.
request.removeHeader('Content-Type');
request.reusedSocket
#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.
const http = require('http');
// Server has a 5 seconds keep-alive timeout by default
http
.createServer((req, res) => {
res.write('hello\n');
res.end();
})
.listen(3000);
setInterval(() => {
// Adapting a keep-alive agent
http.get('http://localhost:3000', { agent }, (res) => {
res.on('data', (data) => {
// Do nothing
});
});
}, 5000); // Sending request on 5s interval so it's easy to hit idle timeout
By marking a request whether it reused socket or not, we can do automatic error retry base on it.
const http = require('http');
const agent = new http.Agent({ keepAlive: true });
function retriableRequest() {
const req = http
.get('http://localhost:3000', { agent }, (res) => {
// ...
})
.on('error', (err) => {
// Check if retry is needed
if (req.reusedSocket && err.code === 'ECONNRESET') {
retriableRequest();
}
});
}
retriableRequest();
request.setHeader(name, value)
#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.
request.setHeader('Content-Type', 'application/json');
or
request.setHeader('Cookie', ['type=ninja', 'language=javascript']);
request.setNoDelay([noDelay])
#noDelay
<boolean>Once a socket is assigned to this request and is connected
socket.setNoDelay()
will be called.
request.setSocketKeepAlive([enable][, initialDelay])
#Once a socket is assigned to this request and is connected
socket.setKeepAlive()
will be called.
request.setTimeout(timeout[, callback])
#Version | Changes |
---|---|
v9.0.0 | Consistently set socket timeout only when the socket connects. |
v0.5.9 | Added in: 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.Once a socket is assigned to this request and is connected
socket.setTimeout()
will be called.
request.socket
#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. The socket
may also be accessed via request.connection
.
const http = require('http');
const options = {
host: 'www.google.com',
};
const req = http.get(options);
req.end();
req.once('response', (res) => {
const ip = req.socket.localAddress;
const port = req.socket.localPort;
console.log(`Your IP address is ${ip} and your source port is ${port}.`);
// Consume response object
});
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>.
request.writableEnded
#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.
request.writableFinished
#Is true
if all data has been flushed to the underlying system, immediately
before the 'finish'
event is emitted.
request.write(chunk[, encoding][, callback])
#chunk
<string> | <Buffer>encoding
<string>callback
<Function>Sends a chunk of the body. By calling this method
many times, a request body can be sent to a
server. In that case, it is suggested to use the
['Transfer-Encoding', 'chunked']
header line when
creating 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.
http.Server
#'checkContinue'
#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.
'checkExpectation'
#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.
'clientError'
#Version | Changes |
---|---|
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 |
v6.0.0 | The default action of calling |
v0.1.94 | Added in: 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 it is
immediately destroyed.
socket
is the net.Socket
object that the error originated from.
const http = require('http');
const server = http.createServer((req, res) => {
res.end();
});
server.on('clientError', (err, socket) => {
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
server.listen(8000);
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.'close'
#Emitted when the server closes.
'connect'
#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.
'connection'
#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.connection
.
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>.
'request'
#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).
'upgrade'
#Version | Changes |
---|---|
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 | Added in: 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>.
server.close([callback])
#callback
<Function>Stops the server from accepting new connections. See net.Server.close()
.
server.headersTimeout
#60000
Limit the amount of time the parser will wait to receive the complete HTTP headers.
In case of inactivity, the rules defined in server.timeout
apply. However,
that inactivity based timeout would still allow the connection to be kept open
if the headers are being sent very slowly (by default, up to a byte per 2
minutes). In order to prevent this, whenever header data arrives an additional
check is made that more than server.headersTimeout
milliseconds has not
passed since the connection was established. If the check fails, a 'timeout'
event is emitted on the server object, and (by default) the socket is destroyed.
See server.timeout
for more information on how timeout behavior can be
customized.
server.listen()
#Starts the HTTP server listening for connections.
This method is identical to server.listen()
from net.Server
.
server.listening
#server.maxHeadersCount
#2000
Limits maximum incoming headers count. If set to 0, no limit will be applied.
server.setTimeout([msecs][, callback])
#Version | Changes |
---|---|
v13.0.0 | The default timeout changed from 120s to 0 (no timeout). |
v0.9.12 | Added in: v0.9.12 |
msecs
<number> Default: 0 (no timeout)callback
<Function>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.
server.timeout
#Version | Changes |
---|---|
v13.0.0 | The default timeout changed from 120s to 0 (no timeout). |
v0.9.12 | Added in: v0.9.12 |
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.
server.keepAliveTimeout
#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.
http.ServerResponse
#This object is created internally by an HTTP server, not by the user. It is
passed as the second parameter to the 'request'
event.
'close'
#Indicates that the underlying connection was terminated.
'finish'
#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.
response.addTrailers(headers)
#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.,
response.writeHead(200, { 'Content-Type': 'text/plain',
'Trailer': 'Content-MD5' });
response.write(fileData);
response.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' });
response.end();
Attempting to set a header field name or value that contains invalid characters
will result in a TypeError
being thrown.
response.connection
#response.socket
.See response.socket
.
response.cork()
#See writable.cork()
.
response.end([data[, encoding]][, callback])
#Version | Changes |
---|---|
v10.0.0 | This method now returns a reference to |
v0.1.90 | Added in: v0.1.90 |
data
<string> | <Buffer>encoding
<string>callback
<Function>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.
response.finished
#response.writableEnded
.The response.finished
property will be true
if response.end()
has been called.
response.flushHeaders()
#Flushes the response headers. See also: request.flushHeaders()
.
response.getHeader(name)
#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()
.
response.setHeader('Content-Type', 'text/html');
response.setHeader('Content-Length', Buffer.byteLength(body));
response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
const contentType = response.getHeader('content-type');
// contentType is 'text/html'
const contentLength = response.getHeader('Content-Length');
// contentLength is of type number
const setCookie = response.getHeader('set-cookie');
// setCookie is of type string[]
response.getHeaderNames()
#Returns an array containing the unique names of the current outgoing headers. All header names are lowercase.
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 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.
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 the
outgoing headers. The header name matching is case-insensitive.
const hasContentType = response.hasHeader('content-type');
response.headersSent
#Boolean (read-only). True if headers were sent, false otherwise.
response.removeHeader(name)
#name
<string>Removes a header that's queued for implicit sending.
response.removeHeader('Content-Encoding');
response.sendDate
#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.
response.setHeader(name, value)
#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.
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 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.
// Returns content-type = text/plain
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.setHeader('X-Foo', 'bar');
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('ok');
});
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()
.
response.setTimeout(msecs[, callback])
#msecs
<number>callback
<Function>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.
response.socket
#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. The socket
may also be accessed
via response.connection
.
const http = require('http');
const server = http.createServer((req, res) => {
const ip = res.socket.remoteAddress;
const port = res.socket.remotePort;
res.end(`Your IP address is ${ip} and your source port is ${port}.`);
}).listen(3000);
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>.
response.statusCode
#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.
response.statusCode = 404;
After response header was sent to the client, this property indicates the status code which was sent out.
response.statusMessage
#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.
response.statusMessage = 'Not found';
After response header was sent to the client, this property indicates the status message which was sent out.
response.uncork()
#See writable.uncork()
.
response.writableEnded
#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.
response.writableFinished
#Is true
if all data has been flushed to the underlying system, immediately
before the 'finish'
event is emitted.
response.write(chunk[, encoding][, callback])
#chunk
<string> | <Buffer>encoding
<string> Default: 'utf8'
callback
<Function>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 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.
response.writeContinue()
#Sends a HTTP/1.1 100 Continue message to the client, indicating that
the request body should be sent. See the 'checkContinue'
event on
Server
.
response.writeHead(statusCode[, statusMessage][, headers])
#Version | Changes |
---|---|
v11.10.0 | Return |
v5.11.0, v4.4.5 | A |
v0.1.30 | Added in: v0.1.30 |
statusCode
<number>statusMessage
<string>headers
<Object>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.
Returns a reference to the ServerResponse
, so that calls can be chained.
const body = 'hello world';
response
.writeHead(200, {
'Content-Length': Buffer.byteLength(body),
'Content-Type': 'text/plain'
})
.end(body);
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.
// Returns content-type = text/plain
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.setHeader('X-Foo', 'bar');
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('ok');
});
Content-Length
is given in bytes, not characters. Use
Buffer.byteLength()
to determine the length of the body in bytes. Node.js
does not 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 TypeError
being thrown.
response.writeProcessing()
#Sends a HTTP/1.1 102 Processing message to the client, indicating that the request body should be sent.
http.IncomingMessage
#Version | Changes |
---|---|
v13.1.0 | The |
v0.1.17 | Added in: v0.1.17 |
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.
'aborted'
#Emitted when the request has been aborted.
'close'
#Indicates that the underlying connection was closed.
message.aborted
#The message.aborted
property will be true
if the request has
been aborted.
message.complete
#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:
const req = http.request({
host: '127.0.0.1',
port: 8080,
method: 'POST'
}, (res) => {
res.resume();
res.on('end', () => {
if (!res.complete)
console.error(
'The connection was terminated while the message was still being sent');
});
});
message.destroy([error])
#error
<Error>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.
message.headers
#The request/response headers object.
Key-value pairs of header names and values. Header names are lower-cased.
// Prints something like:
//
// { 'user-agent': 'curl/7.22.0',
// host: '127.0.0.1:8000',
// accept: '*/*' }
console.log(request.headers);
Duplicates in raw headers are handled in the following ways, depending on the header name:
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
, or user-agent
are discarded.set-cookie
is always an array. Duplicates are added to the array.cookie
headers, the values are joined together with '; '.message.httpVersion
#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.
message.method
#Only valid for request obtained from http.Server
.
The request method as a string. Read only. Examples: 'GET'
, 'DELETE'
.
message.rawHeaders
#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.
// 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);
message.rawTrailers
#The raw request/response trailer keys and values exactly as they were
received. Only populated at the 'end'
event.
message.setTimeout(msecs[, callback])
#msecs
<number>callback
<Function>Calls message.connection.setTimeout(msecs, callback)
.
message.socket
#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>.
message.statusCode
#Only valid for response obtained from http.ClientRequest
.
The 3-digit HTTP response status code. E.G. 404
.
message.statusMessage
#Only valid for response obtained from http.ClientRequest
.
The HTTP response status message (reason phrase). E.G. OK
or Internal Server Error
.
message.trailers
#The request/response trailers object. Only populated at the 'end'
event.
message.url
#Only valid for request obtained from http.Server
.
Request URL string. This contains only the URL that is present in the actual HTTP request. If the request is:
GET /status?name=ryan HTTP/1.1\r\n
Accept: text/plain\r\n
\r\n
To parse the URL into its parts:
new URL(request.url, `http://${request.headers.host}`);
When request.url
is '/status?name=ryan'
and
request.headers.host
is 'localhost:3000'
:
$ node
> new URL(request.url, `http://${request.headers.host}`)
URL {
href: 'http://localhost:3000/status?name=ryan',
origin: 'http://localhost:3000',
protocol: 'http:',
username: '',
password: '',
host: 'localhost:3000',
hostname: 'localhost',
port: '3000',
pathname: '/status',
search: '?name=ryan',
searchParams: URLSearchParams { 'name' => 'ryan' },
hash: ''
}
http.METHODS
#A list of the HTTP methods that are supported by the parser.
http.STATUS_CODES
#A collection of all the standard HTTP response status codes, and the
short description of each. For example, http.STATUS_CODES[404] === 'Not Found'
.
http.createServer([options][, requestListener])
#Version | Changes |
---|---|
v13.8.0 | The |
v13.3.0 | The |
v9.6.0, v8.12.0 | The |
v0.1.13 | Added in: v0.1.13 |
options
<Object>
IncomingMessage
<http.IncomingMessage> Specifies the IncomingMessage
class to be used. Useful for extending the original IncomingMessage
.
Default: IncomingMessage
.ServerResponse
<http.ServerResponse> Specifies the ServerResponse
class
to be used. Useful for extending the original ServerResponse
. Default:
ServerResponse
.insecureHTTPParser
<boolean> Use an insecure HTTP parser that accepts
invalid HTTP headers when true
. 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 (16KB).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.
http.get(options[, callback])
#http.get(url[, options][, callback])
#Version | Changes |
---|---|
v10.9.0 | The |
v7.5.0 | The |
v0.3.6 | Added in: v0.3.6 |
url
<string> | <URL>options
<Object> Accepts the same options
as
http.request()
, with the method
always set to GET
.
Properties that are inherited from the prototype are ignored.callback
<Function>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:
http.get('http:///dist/index.json', (res) => {
const { statusCode } = res;
const contentType = res.headers['content-type'];
let error;
if (statusCode !== 200) {
error = new Error('Request Failed.\n' +
`Status Code: ${statusCode}`);
} else if (!/^application\/json/.test(contentType)) {
error = new Error('Invalid content-type.\n' +
`Expected application/json but received ${contentType}`);
}
if (error) {
console.error(error.message);
// Consume response data to free up memory
res.resume();
return;
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
try {
const parsedData = JSON.parse(rawData);
console.log(parsedData);
} catch (e) {
console.error(e.message);
}
});
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});
http.globalAgent
#Global instance of Agent
which is used as the default for all HTTP client
requests.
http.maxHeaderSize
#Read-only property specifying the maximum allowed size of HTTP headers in bytes.
Defaults to 8KB. Configurable using the --max-http-header-size
CLI option.
This can be overridden for servers and client requests by passing the
maxHeaderSize
option.
http.request(options[, callback])
#http.request(url[, options][, callback])
#Version | Changes |
---|---|
v13.8.0 | The |
v13.3.0 | The |
v10.9.0 | The |
v7.5.0 | The |
v0.3.6 | Added in: v0.3.6 |
url
<string> | <URL>options
<Object>
agent
<http.Agent> | <boolean> Controls Agent
behavior. Possible
values:
undefined
(default): use http.globalAgent
for this host and port.Agent
object: explicitly use the passed in Agent
.false
: causes a new Agent
with default values to be used.auth
<string> Basic authentication i.e. 'user:password'
to compute an
Authorization header.createConnection
<Function> A function that produces a socket/stream to
use for the request when the agent
option is not used. This can be used to
avoid creating a custom Agent
class just to override the default
createConnection
function. See agent.createConnection()
for more
details. Any Duplex
stream is a valid return value.defaultPort
<number> Default port for the protocol. Default:
agent.defaultPort
if an Agent
is used, else undefined
.family
<number> IP address family to use when resolving host
or
hostname
. Valid values are 4
or 6
. When unspecified, both IP v4 and
v6 will be used.headers
<Object> An object containing request headers.host
<string> A domain name or IP address of the server to issue the
request to. Default: 'localhost'
.hostname
<string> Alias for host
. To support url.parse()
,
hostname
will be used if both host
and hostname
are specified.insecureHTTPParser
<boolean> Use an insecure HTTP parser that accepts
invalid HTTP headers when true
. 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.lookup
<Function> Custom lookup function. Default: dns.lookup()
.maxHeaderSize
<number> Optionally overrides the value of
--max-http-header-size
for requests received from the server, i.e.
the maximum length of response headers in bytes.
Default: 16384 (16KB).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,
else 80
.protocol
<string> Protocol to use. Default: 'http:'
.setHost
<boolean>: Specifies whether or not to automatically add the
Host
header. Defaults to true
.socketPath
<string> Unix Domain Socket (cannot be used if one of host
or port
is specified, 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.callback
<Function>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.
const postData = querystring.stringify({
'msg': 'Hello World!'
});
const options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
const req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
// Write data to request body
req.write(postData);
req.end();
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
:
const options = new URL('http://abc:xyz@example.com');
const req = http.request(options, (res) => {
// ...
});
In a successful request, the following events will be emitted in the following order:
'socket'
'response'
'data'
any number of times, on the res
object
('data'
will not be emitted at all if the response body is empty, for
instance, in most redirects)'end'
on the res
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 the res
object'aborted'
on the res
object'close'
'close'
on the res
objectIf 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 the res
objectreq.destroy()
called here)'aborted'
on the res
object'close'
'close'
on the res
objectIf 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 the res
objectreq.abort()
called here)'abort'
'aborted'
on the res
object'close'
'close'
on the res
objectSetting the timeout
option or using the setTimeout()
function will
not abort the request or do anything besides add a 'timeout'
event.
|