Spec-Zone.ru › Deno 2

http

To use the HTTP server and client one must import the node:http module.

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:

{ "content-length": "123",
  "content-type": "text/plain",
  "connection": "keep-alive",
  "host": "example.com",
  "accept": "*" }

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:

[ 'ConTent-Length', '123456',
  'content-LENGTH', '123',
  'content-type', 'text/plain',
  'CONNECTION', 'keep-alive',
  'Host', 'example.com',
  'accepT', '*' ]

Usage in Deno

import * as mod from "node:http";

class Agent

extends EventEmitter

Usage in Deno

import { Agent } from "node:http";

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:

http.get(options, (res) => {
  // Do stuff
}).on('socket', (socket) => {
  socket.emit('agentRemove');
});

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:

http.get({
  hostname: 'localhost',
  port: 80,
  path: '/',
  agent: false,  // Create a new agent just for this one request
}, (res) => {
  // Do stuff with response
});

options in socket.connect() are also supported.

To configure any of them, a custom Agent instance must be created.

import http from 'node:http';
const keepAliveAgent = new http.Agent({ keepAlive: true });
options.agent = keepAliveAgent;
http.request(options, onResponseCallback)

Constructors

Agent(opts?: AgentOptions)
new

Properties

freeSockets: ReadOnlyDict<Socket[]>
readonly

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'.

maxFreeSockets: number

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.

maxSockets: number

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().

maxTotalSockets: number

By default set to Infinity. Determines how many concurrent sockets the agent can have open. Unlike maxSockets, this parameter applies across all origins.

requests: ReadOnlyDict<IncomingMessage[]>
readonly

An object which contains queues of requests that have not yet been assigned to sockets. Do not modify.

sockets: ReadOnlyDict<Socket[]>
readonly

An object which contains arrays of sockets currently in use by the agent. Do not modify.

Methods

destroy(): void

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.


class ClientRequest

extends OutgoingMessage

Usage in Deno

import { ClientRequest } from "node:http";
Deno compatibility

Constructor option createConnection is not supported.

This object is created internally and returned from 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 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. If response.strictContentLength is set to true, 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.

Constructors

ClientRequest(
url:
string
| URL
| ClientRequestArgs
,
cb?: (res: IncomingMessage) => void,
)
new

Properties

aborted: boolean
deprecated

The request.aborted property will be true if the request has been aborted.

host: string

The request host.

maxHeadersCount: number

Limits maximum response headers count. If set to 0, no limit will be applied.

method: string

The request method.

path: string

The request path.

protocol: string

The request protocol.

reusedSocket: boolean

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.

import http from 'node: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.

import http from 'node: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 &#x26;&#x26; err.code === 'ECONNRESET') {
        retriableRequest();
      }
    });
}

retriableRequest();

Methods

abort(): void
deprecated

Marks the request as aborting. Calling this will cause remaining data in the response to be dropped and the socket to be destroyed.

addListener(
event: "abort",
listener: () => void,
): this
deprecated
addListener(
event: "connect",
listener: (
response: IncomingMessage,
socket: Socket,
head: Buffer,
) => void
,
): this
addListener(
event: "continue",
listener: () => void,
): this
addListener(
event: "information",
listener: (info: InformationEvent) => void,
): this
addListener(
event: "response",
listener: (response: IncomingMessage) => void,
): this
addListener(
event: "socket",
listener: (socket: Socket) => void,
): this
addListener(
event: "timeout",
listener: () => void,
): this
addListener(
event: "upgrade",
listener: (
response: IncomingMessage,
socket: Socket,
head: Buffer,
) => void
,
): this
addListener(
event: "close",
listener: () => void,
): this
addListener(
event: "drain",
listener: () => void,
): this
addListener(
event: "error",
listener: (err: Error) => void,
): this
addListener(
event: "finish",
listener: () => void,
): this
addListener(
event: "pipe",
listener: (src: stream.Readable) => void,
): this
addListener(
event: "unpipe",
listener: (src: stream.Readable) => void,
): this
addListener(
event: string | symbol,
listener: (...args: any[]) => void,
): this
getRawHeaderNames(): string[]

Returns an array containing the unique names of the current outgoing raw headers. Header names are returned with their exact casing being set.

request.setHeader('Foo', 'bar');
request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);

const headerNames = request.getRawHeaderNames();
// headerNames === ['Foo', 'Set-Cookie']
on(
event: "abort",
listener: () => void,
): this
deprecated
on(
event: "connect",
listener: (
response: IncomingMessage,
socket: Socket,
head: Buffer,
) => void
,
): this
on(
event: "continue",
listener: () => void,
): this
on(
event: "information",
listener: (info: InformationEvent) => void,
): this
on(
event: "response",
listener: (response: IncomingMessage) => void,
): this
on(
event: "socket",
listener: (socket: Socket) => void,
): this
on(
event: "timeout",
listener: () => void,
): this
on(
event: "upgrade",
listener: (
response: IncomingMessage,
socket: Socket,
head: Buffer,
) => void
,
): this
on(
event: "close",
listener: () => void,
): this
on(
event: "drain",
listener: () => void,
): this
on(
event: "error",
listener: (err: Error) => void,
): this
on(
event: "finish",
listener: () => void,
): this
on(
event: "pipe",
listener: (src: stream.Readable) => void,
): this
on(
event: "unpipe",
listener: (src: stream.Readable) => void,
): this
on(
event: string | symbol,
listener: (...args: any[]) => void,
): this
onSocket(socket: Socket): void
once(
event: "abort",
listener: () => void,
): this
deprecated
once(
event: "connect",
listener: (
response: IncomingMessage,
socket: Socket,
head: Buffer,
) => void
,
): this
once(
event: "continue",
listener: () => void,
): this
once(
event: "information",
listener: (info: InformationEvent) => void,
): this
once(
event: "response",
listener: (response: IncomingMessage) => void,
): this
once(
event: "socket",
listener: (socket: Socket) => void,
): this
once(
event: "timeout",
listener: () => void,
): this
once(
event: "upgrade",
listener: (
response: IncomingMessage,
socket: Socket,
head: Buffer,
) => void
,
): this
once(
event: "close",
listener: () => void,
): this
once(
event: "drain",
listener: () => void,
): this
once(
event: "error",
listener: (err: Error) => void,
): this
once(
event: "finish",
listener: () => void,
): this
once(
event: "pipe",
listener: (src: stream.Readable) => void,
): this
once(
event: "unpipe",
listener: (src: stream.Readable) => void,
): this
once(
event: string | symbol,
listener: (...args: any[]) => void,
): this
prependListener(
event: "abort",
listener: () => void,
): this
deprecated
prependListener(
event: "connect",
listener: (
response: IncomingMessage,
socket: Socket,
head: Buffer,
) => void
,
): this
prependListener(
event: "continue",
listener: () => void,
): this
prependListener(
event: "information",
listener: (info: InformationEvent) => void,
): this
prependListener(
event: "response",
listener: (response: IncomingMessage) => void,
): this
prependListener(
event: "socket",
listener: (socket: Socket) => void,
): this
prependListener(
event: "timeout",
listener: () => void,
): this
prependListener(
event: "upgrade",
listener: (
response: IncomingMessage,
socket: Socket,
head: Buffer,
) => void
,
): this
prependListener(
event: "close",
listener: () => void,
): this
prependListener(
event: "drain",
listener: () => void,
): this
prependListener(
event: "error",
listener: (err: Error) => void,
): this
prependListener(
event: "finish",
listener: () => void,
): this
prependListener(
event: "pipe",
listener: (src: stream.Readable) => void,
): this
prependListener(
event: "unpipe",
listener: (src: stream.Readable) => void,
): this
prependListener(
event: string | symbol,
listener: (...args: any[]) => void,
): this
prependOnceListener(
event: "abort",
listener: () => void,
): this
deprecated
prependOnceListener(
event: "connect",
listener: (
response: IncomingMessage,
socket: Socket,
head: Buffer,
) => void
,
): this
prependOnceListener(
event: "continue",
listener: () => void,
): this
prependOnceListener(
event: "information",
listener: (info: InformationEvent) => void,
): this
prependOnceListener(
event: "response",
listener: (response: IncomingMessage) => void,
): this
prependOnceListener(
event: "socket",
listener: (socket: Socket) => void,
): this
prependOnceListener(
event: "timeout",
listener: () => void,
): this
prependOnceListener(
event: "upgrade",
listener: (
response: IncomingMessage,
socket: Socket,
head: Buffer,
) => void
,
): this
prependOnceListener(
event: "close",
listener: () => void,
): this
prependOnceListener(
event: "drain",
listener: () => void,
): this
prependOnceListener(
event: "error",
listener: (err: Error) => void,
): this
prependOnceListener(
event: "finish",
listener: () => void,
): this
prependOnceListener(
event: "pipe",
listener: (src: stream.Readable) => void,
): this
prependOnceListener(
event: "unpipe",
listener: (src: stream.Readable) => void,
): this
prependOnceListener(
event: string | symbol,
listener: (...args: any[]) => void,
): this
setNoDelay(noDelay?: boolean): void

Once a socket is assigned to this request and is connected socket.setNoDelay() will be called.

setSocketKeepAlive(
enable?: boolean,
initialDelay?: number,
): void

Once a socket is assigned to this request and is connected socket.setKeepAlive() will be called.

setTimeout(
timeout: number,
callback?: () => void,
): this

Once a socket is assigned to this request and is connected socket.setTimeout() will be called.


class IncomingMessage

extends stream.Readable

Usage in Deno

import { IncomingMessage } from "node:http";

An IncomingMessage object is created by Server or 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.

Constructors

IncomingMessage(socket: Socket)
new

Properties

aborted: boolean
deprecated

The message.aborted property will be true if the request has been aborted.

complete: boolean

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');
  });
});
connection: Socket
deprecated

Alias for message.socket.

headers: IncomingHttpHeaders

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:

  • 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, or user-agent are discarded. To allow duplicate values of the headers listed above to be joined, use the option joinDuplicateHeaders in request and createServer. See RFC 9110 Section 5.3 for more information.
  • 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 , .
headersDistinct: Dict<string[]>

Similar to message.headers, but there is no join logic and the values are always arrays of strings, even for headers received just once.

// Prints something like:
//
// { 'user-agent': ['curl/7.22.0'],
//   host: ['127.0.0.1:8000'],
//   accept: ['*'] }
console.log(request.headersDistinct);
httpVersion: string

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.

httpVersionMajor: number
httpVersionMinor: number
method: string | undefined
optional

Only valid for request obtained from Server.

The request method as a string. Read only. Examples: 'GET', 'DELETE'.

rawHeaders: 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.

// 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);
rawTrailers: string[]

The raw request/response trailer keys and values exactly as they were received. Only populated at the 'end' event.

socket: 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 or internally nulled.

statusCode: number | undefined
optional

Only valid for response obtained from ClientRequest.

The 3-digit HTTP response status code. E.G. 404.

statusMessage: string | undefined
optional

Only valid for response obtained from ClientRequest.

The HTTP response status message (reason phrase). E.G. OK or Internal Server Error.

trailers: Dict<string>

The request/response trailers object. Only populated at the 'end' event.

trailersDistinct: Dict<string[]>

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.

url: string | undefined
optional

Only valid for request obtained from Server.

Request URL string. This contains only the URL that is present in the actual HTTP request. Take the following request:

GET /status?name=ryan HTTP/1.1
Accept: text/plain

To parse the URL into its parts:

new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`);

When request.url is '/status?name=ryan' and process.env.HOST is undefined:

$ node
> new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`);
URL {
  href: 'http://localhost/status?name=ryan',
  origin: 'http://localhost',
  protocol: 'http:',
  username: '',
  password: '',
  host: 'localhost',
  hostname: 'localhost',
  port: '',
  pathname: '/status',
  search: '?name=ryan',
  searchParams: URLSearchParams { 'name' => 'ryan' },
  hash: ''
}

Ensure that you set process.env.HOST to the server's host name, or consider replacing this part entirely. If using req.headers.host, ensure proper validation is used, as clients may specify a custom Host header.

Methods

destroy(error?: Error): this

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.

setTimeout(
msecs: number,
callback?: () => void,
): this

Calls message.socket.setTimeout(msecs, callback).


class OutgoingMessage

extends stream.Writable

Usage in Deno

import { OutgoingMessage } from "node:http";

This class serves as the parent class of ClientRequest and ServerResponse. It is an abstract outgoing message from the perspective of the participants of an HTTP transaction.

Constructors

OutgoingMessage()
new

Type Parameters

Request extends IncomingMessage = IncomingMessage

Properties

chunkedEncoding: boolean
connection: Socket | null
deprecated
readonly

Alias of outgoingMessage.socket.

finished: boolean
deprecated
headersSent: boolean
readonly

Read-only. true if the headers were sent, otherwise false.

req: Request
readonly
sendDate: boolean
shouldKeepAlive: boolean
socket: Socket | null
readonly

Reference to the underlying socket. Usually, users will not want to access this property.

After calling outgoingMessage.end(), this property will be nulled.

useChunkedEncodingByDefault: boolean

Methods

addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void

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.

message.writeHead(200, { 'Content-Type': 'text/plain',
                         'Trailer': 'Content-MD5' });
message.write(fileData);
message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' });
message.end();

Attempting to set a header field name or value that contains invalid characters will result in a TypeError being thrown.

appendHeader(
name: string,
value: string | readonly string[],
): this

Append a single header value to the header object.

If the value is an array, this is equivalent to calling this method multiple times.

If there were no previous values for the header, this is equivalent to 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 ; .

flushHeaders(): void

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.

getHeader(name: string):
number
| string
| string[]
| undefined

Gets the value of the HTTP header with the given name. If that header is not set, the returned value will be undefined.

getHeaderNames(): string[]

Returns an array containing the unique names of the current outgoing headers. All names are lowercase.

getHeaders(): OutgoingHttpHeaders

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.

outgoingMessage.setHeader('Foo', 'bar');
outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);

const headers = outgoingMessage.getHeaders();
// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }
hasHeader(name: string): boolean

Returns true if the header identified by name is currently set in the outgoing headers. The header name is case-insensitive.

const hasContentType = outgoingMessage.hasHeader('content-type');
removeHeader(name: string): void

Removes a header that is queued for implicit sending.

outgoingMessage.removeHeader('Content-Encoding');
setHeader(
name: string,
value:
number
| string
| readonly string[]
,
): this

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.

setHeaders(headers: Headers | Map<string,
number
| string
| readonly string[]
>
): this

Sets multiple header values for implicit headers. headers must be an instance of Headers or Map, if a header already exists in the to-be-sent headers, its value will be replaced.

const headers = new Headers({ foo: 'bar' });
outgoingMessage.setHeaders(headers);

or

const headers = new Map([['foo', 'bar']]);
outgoingMessage.setHeaders(headers);

When headers have been set with outgoingMessage.setHeaders(), 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) => {
  const headers = new Headers({ 'Content-Type': 'text/html' });
  res.setHeaders(headers);
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('ok');
});
setTimeout(
msecs: number,
callback?: () => void,
): this

Once a socket is associated with the message and is connected, socket.setTimeout() will be called with msecs as the first parameter.


class Server

extends NetServer

Usage in Deno

import { Server } from "node:http";

Constructors

Server(requestListener?: RequestListener<Request, Response>)
new
Server(
options: ServerOptions<Request, Response>,
requestListener?: RequestListener<Request, Response>,
)
new

Type Parameters

Request extends IncomingMessage = IncomingMessage
Response extends ServerResponse = ServerResponse

Properties

headersTimeout: number

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.

keepAliveTimeout: number

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.

maxHeadersCount: number | null

Limits maximum incoming headers count. If set to 0, no limit will be applied.

maxRequestsPerSocket: number | null

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.

requestTimeout: number

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.

timeout: number

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.

Methods

addListener(
event: string,
listener: (...args: any[]) => void,
): this
addListener(
event: "close",
listener: () => void,
): this
addListener(
event: "connection",
listener: (socket: Socket) => void,
): this
addListener(
event: "error",
listener: (err: Error) => void,
): this
addListener(
event: "listening",
listener: () => void,
): this
addListener(
event: "checkContinue",
listener: RequestListener<Request, Response>,
): this
addListener(
event: "checkExpectation",
listener: RequestListener<Request, Response>,
): this
addListener(
event: "clientError",
listener: (
err: Error,
socket: stream.Duplex,
) => void
,
): this
addListener(
event: "connect",
listener: (
req: InstanceType<Request>,
socket: stream.Duplex,
head: Buffer,
) => void
,
): this
addListener(
event: "dropRequest",
listener: (
req: InstanceType<Request>,
socket: stream.Duplex,
) => void
,
): this
addListener(
event: "request",
listener: RequestListener<Request, Response>,
): this
addListener(
event: "upgrade",
listener: (
req: InstanceType<Request>,
socket: stream.Duplex,
head: Buffer,
) => void
,
): this
closeAllConnections(): void

Closes all connections connected to this server.

closeIdleConnections(): void

Closes all connections connected to this server which are not sending a request or waiting for a response.

emit(
event: string,
...args: any[],
): boolean
emit(event: "close"): boolean
emit(
event: "connection",
socket: Socket,
): boolean
emit(
event: "error",
err: Error,
): boolean
emit(event: "listening"): boolean
emit(
event: "checkContinue",
req: InstanceType<Request>,
res: InstanceType<Response> & { req: InstanceType<Request>; },
): boolean
emit(
event: "checkExpectation",
req: InstanceType<Request>,
res: InstanceType<Response> & { req: InstanceType<Request>; },
): boolean
emit(
event: "clientError",
err: Error,
socket: stream.Duplex,
): boolean
emit(
event: "connect",
req: InstanceType<Request>,
socket: stream.Duplex,
head: Buffer,
): boolean
emit(
event: "dropRequest",
req: InstanceType<Request>,
socket: stream.Duplex,
): boolean
emit(
event: "request",
req: InstanceType<Request>,
res: InstanceType<Response> & { req: InstanceType<Request>; },
): boolean
emit(
event: "upgrade",
req: InstanceType<Request>,
socket: stream.Duplex,
head: Buffer,
): boolean
on(
event: string,
listener: (...args: any[]) => void,
): this
on(
event: "close",
listener: () => void,
): this
on(
event: "connection",
listener: (socket: Socket) => void,
): this
on(
event: "error",
listener: (err: Error) => void,
): this
on(
event: "listening",
listener: () => void,
): this
on(
event: "checkContinue",
listener: RequestListener<Request, Response>,
): this
on(
event: "checkExpectation",
listener: RequestListener<Request, Response>,
): this
on(
event: "clientError",
listener: (
err: Error,
socket: stream.Duplex,
) => void
,
): this
on(
event: "connect",
listener: (
req: InstanceType<Request>,
socket: stream.Duplex,
head: Buffer,
) => void
,
): this
on(
event: "dropRequest",
listener: (
req: InstanceType<Request>,
socket: stream.Duplex,
) => void
,
): this
on(
event: "request",
listener: RequestListener<Request, Response>,
): this
on(
event: "upgrade",
listener: (
req: InstanceType<Request>,
socket: stream.Duplex,
head: Buffer,
) => void
,
): this
once(
event: string,
listener: (...args: any[]) => void,
): this
once(
event: "close",
listener: () => void,
): this
once(
event: "connection",
listener: (socket: Socket) => void,
): this
once(
event: "error",
listener: (err: Error) => void,
): this
once(
event: "listening",
listener: () => void,
): this
once(
event: "checkContinue",
listener: RequestListener<Request, Response>,
): this
once(
event: "checkExpectation",
listener: RequestListener<Request, Response>,
): this
once(
event: "clientError",
listener: (
err: Error,
socket: stream.Duplex,
) => void
,
): this
once(
event: "connect",
listener: (
req: InstanceType<Request>,
socket: stream.Duplex,
head: Buffer,
) => void
,
): this
once(
event: "dropRequest",
listener: (
req: InstanceType<Request>,
socket: stream.Duplex,
) => void
,
): this
once(
event: "request",
listener: RequestListener<Request, Response>,
): this
once(
event: "upgrade",
listener: (
req: InstanceType<Request>,
socket: stream.Duplex,
head: Buffer,
) => void
,
): this
prependListener(
event: string,
listener: (...args: any[]) => void,
): this
prependListener(
event: "close",
listener: () => void,
): this
prependListener(
event: "connection",
listener: (socket: Socket) => void,
): this
prependListener(
event: "error",
listener: (err: Error) => void,
): this
prependListener(
event: "listening",
listener: () => void,
): this
prependListener(
event: "checkContinue",
listener: RequestListener<Request, Response>,
): this
prependListener(
event: "checkExpectation",
listener: RequestListener<Request, Response>,
): this
prependListener(
event: "clientError",
listener: (
err: Error,
socket: stream.Duplex,
) => void
,
): this
prependListener(
event: "connect",
listener: (
req: InstanceType<Request>,
socket: stream.Duplex,
head: Buffer,
) => void
,
): this
prependListener(
event: "dropRequest",
listener: (
req: InstanceType<Request>,
socket: stream.Duplex,
) => void
,
): this
prependListener(
event: "request",
listener: RequestListener<Request, Response>,
): this
prependListener(
event: "upgrade",
listener: (
req: InstanceType<Request>,
socket: stream.Duplex,
head: Buffer,
) => void
,
): this
prependOnceListener(
event: string,
listener: (...args: any[]) => void,
): this
prependOnceListener(
event: "close",
listener: () => void,
): this
prependOnceListener(
event: "connection",
listener: (socket: Socket) => void,
): this
prependOnceListener(
event: "error",
listener: (err: Error) => void,
): this
prependOnceListener(
event: "listening",
listener: () => void,
): this
prependOnceListener(
event: "checkContinue",
listener: RequestListener<Request, Response>,
): this
prependOnceListener(
event: "checkExpectation",
listener: RequestListener<Request, Response>,
): this
prependOnceListener(
event: "clientError",
listener: (
err: Error,
socket: stream.Duplex,
) => void
,
): this
prependOnceListener(
event: "connect",
listener: (
req: InstanceType<Request>,
socket: stream.Duplex,
head: Buffer,
) => void
,
): this
prependOnceListener(
event: "dropRequest",
listener: (
req: InstanceType<Request>,
socket: stream.Duplex,
) => void
,
): this
prependOnceListener(
event: "request",
listener: RequestListener<Request, Response>,
): this
prependOnceListener(
event: "upgrade",
listener: (
req: InstanceType<Request>,
socket: stream.Duplex,
head: Buffer,
) => void
,
): this
setTimeout(
msecs?: number,
callback?: (socket: Socket) => void,
): this

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.

setTimeout(callback: (socket: Socket) => void): this

class ServerResponse

extends OutgoingMessage<Request>

Usage in Deno

import { ServerResponse } from "node:http";

This object is created internally by an HTTP server, not by the user. It is passed as the second parameter to the 'request' event.

Constructors

ServerResponse(req: Request)
new

Type Parameters

Request extends IncomingMessage = IncomingMessage

Properties

statusCode: number

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.

statusMessage: string

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.

strictContentLength: boolean

If set to true, Node.js will check whether the Content-Length header value and the size of the body, in bytes, are equal. Mismatching the Content-Length header value will result in an Error being thrown, identified by code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'.

Methods

assignSocket(socket: Socket): void
detachSocket(socket: Socket): void
writeContinue(callback?: () => void): void

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.

writeEarlyHints(
hints: Record<string, string | string[]>,
callback?: () => void,
): void

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

const earlyHintsLink = '</styles.css>; rel=preload; as=style';
response.writeEarlyHints({
  'link': earlyHintsLink,
});

const earlyHintsLinks = [
  '</styles.css>; rel=preload; as=style',
  '</scripts.js>; rel=preload; as=script',
];
response.writeEarlyHints({
  'link': earlyHintsLinks,
  'x-trace-id': 'id for diagnostics',
});

const earlyHintsCallback = () => console.log('early hints message sent');
response.writeEarlyHints({
  'link': earlyHintsLinks,
}, earlyHintsCallback);
writeHead(
statusCode: number,
statusMessage?: string,
headers?: OutgoingHttpHeaders | OutgoingHttpHeader[],
): this

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.

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 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.

writeHead(
statusCode: number,
headers?: OutgoingHttpHeaders | OutgoingHttpHeader[],
): this
writeProcessing(): void

Sends a HTTP/1.1 102 Processing message to the client, indicating that the request body should be sent.


function createServer

Usage in Deno

import { createServer } from "node:http";

Overload 1

createServer<
Request extends IncomingMessage = IncomingMessage,
Response extends ServerResponse = ServerResponse,
>
(requestListener?: RequestListener<Request, Response>): Server<Request, Response>

Returns a new instance of Server.

The requestListener is a function which is automatically added to the 'request' event.

import http from 'node:http';

// Create a local server to receive data from
const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({
    data: 'Hello World!',
  }));
});

server.listen(8000);
import http from 'node:http';

// Create a local server to receive data from
const server = http.createServer();

// Listen to the request event
server.on('request', (request, res) => {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({
    data: 'Hello World!',
  }));
});

server.listen(8000);

Type Parameters

Request extends IncomingMessage = IncomingMessage
Response extends ServerResponse = ServerResponse

Parameters

requestListener: RequestListener<Request, Response>
optional

Return Type

Server<Request, Response>

Overload 2

createServer<
Request extends IncomingMessage = IncomingMessage,
Response extends ServerResponse = ServerResponse,
>
(
options: ServerOptions<Request, Response>,
requestListener?: RequestListener<Request, Response>,
): Server<Request, Response>

Type Parameters

Request extends IncomingMessage = IncomingMessage
Response extends ServerResponse = ServerResponse

Parameters

options: ServerOptions<Request, Response>
requestListener: RequestListener<Request, Response>
optional

Return Type

Server<Request, Response>

function get

Usage in Deno

import { get } from "node:http";

Overload 1

get(
options:
RequestOptions
| string
| URL
,
callback?: (res: IncomingMessage) => void,
): ClientRequest
Deno compatibility

Constructor option createConnection is not supported.

Since most requests are GET requests without bodies, Node.js provides this convenience method. The only difference between this method and request is that it sets the method to GET by default and calls req.end() automatically. The callback must take care to consume the response data for reasons stated in ClientRequest section.

The callback is invoked with a single argument that is an instance of IncomingMessage.

JSON fetching example:

http.get('http://localhost:8000/', (res) => {
  const { statusCode } = res;
  const contentType = res.headers['content-type'];

  let error;
  // Any 2xx status code signals a successful response but
  // here we're only checking for 200.
  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}`);
});

// Create a local server to receive data from
const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({
    data: 'Hello World!',
  }));
});

server.listen(8000);

Parameters

options:
RequestOptions
| string
| URL

Accepts the same options as request, with the method set to GET by default.

callback: (res: IncomingMessage) => void
optional

Return Type

ClientRequest

Overload 2

get(
url: string | URL,
options: RequestOptions,
callback?: (res: IncomingMessage) => void,
): ClientRequest
Deno compatibility

Constructor option createConnection is not supported.

Parameters

url: string | URL
options: RequestOptions
callback: (res: IncomingMessage) => void
optional

Return Type

ClientRequest

function request

Usage in Deno

import { request } from "node:http";

Overload 1

request(
options:
RequestOptions
| string
| URL
,
callback?: (res: IncomingMessage) => void,
): ClientRequest
Deno compatibility

Constructor option createConnection is not supported.

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 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.

import http from 'node:http';
import { Buffer } from 'node:buffer';

const postData = JSON.stringify({
  'msg': 'Hello World!',
});

const options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    '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
  • (connection closed here)
  • 'aborted' on the res object
  • 'close'
  • 'error' on the res object with an error with message 'Error: aborted' and code 'ECONNRESET'
  • 'close' on the res 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', or the error with which req.destroy() was called
  • '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', or the error with which req.destroy() was called
  • '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 object
  • (req.destroy() called here)
  • 'aborted' on the res object
  • 'close'
  • 'error' on the res object with an error with message 'Error: aborted' and code 'ECONNRESET', or the error with which req.destroy() was called
  • 'close' on the res 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 the res object
  • (req.abort() called here)
  • 'abort'
  • 'aborted' on the res object
  • 'error' on the res object with an error with message 'Error: aborted' and code 'ECONNRESET'.
  • 'close'
  • 'close' on the res 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. Specifically, the 'error' event will be emitted with an error with the message 'AbortError: The operation was aborted', the code 'ABORT_ERR' and the cause, if one was provided.

Parameters

options:
RequestOptions
| string
| URL
callback: (res: IncomingMessage) => void
optional

Return Type

ClientRequest

Overload 2

request(
url: string | URL,
options: RequestOptions,
callback?: (res: IncomingMessage) => void,
): ClientRequest
Deno compatibility

Constructor option createConnection is not supported.

Parameters

url: string | URL
options: RequestOptions
callback: (res: IncomingMessage) => void
optional

Return Type

ClientRequest

function setMaxIdleHTTPParsers

Usage in Deno

import { setMaxIdleHTTPParsers } from "node:http";
setMaxIdleHTTPParsers(max: number): void

Set the maximum number of idle HTTP parsers.

Parameters

max: number = 1000
optional

Return Type

void

function validateHeaderName

Usage in Deno

import { validateHeaderName } from "node:http";
validateHeaderName(name: string): void

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.

Example:

import { validateHeaderName } from 'node:http';

try {
  validateHeaderName('');
} catch (err) {
  console.error(err instanceof TypeError); // --> true
  console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN'
  console.error(err.message); // --> 'Header name must be a valid HTTP token [""]'
}

Parameters

name: string

Return Type

void

function validateHeaderValue

Usage in Deno

import { validateHeaderValue } from "node:http";
validateHeaderValue(
name: string,
value: string,
): void

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:

import { validateHeaderValue } from 'node:http';

try {
  validateHeaderValue('x-my-header', undefined);
} catch (err) {
  console.error(err instanceof TypeError); // --> true
  console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true
  console.error(err.message); // --> 'Invalid value "undefined" for header "x-my-header"'
}

try {
  validateHeaderValue('x-my-header', 'oʊmɪɡə');
} catch (err) {
  console.error(err instanceof TypeError); // --> true
  console.error(err.code === 'ERR_INVALID_CHAR'); // --> true
  console.error(err.message); // --> 'Invalid character in header content ["x-my-header"]'
}

Parameters

name: string

Header name

value: string

Header value

Return Type

void

interface AgentOptions

extends Partial<TcpSocketConnectOpts>

Usage in Deno

import { type AgentOptions } from "node:http";

Properties

keepAlive: boolean | undefined
optional

Keep sockets around in a pool to be used by other requests in the future. Default = false

keepAliveMsecs: number | undefined
optional

When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. Only relevant if keepAlive is set to true.

maxSockets: number | undefined
optional

Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity

maxTotalSockets: number | undefined
optional

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 | undefined
optional

Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256.

timeout: number | undefined
optional

Socket timeout in milliseconds. This will set the timeout after the socket is connected.

scheduling:
"fifo"
| "lifo"
| undefined
optional

Scheduling strategy to apply when picking the next free socket to use.


interface ClientRequestArgs

Usage in Deno

import { type ClientRequestArgs } from "node:http";
Deno compatibility

Option createConnection is not supported.

Properties

_defaultAgent: Agent | undefined
optional
agent:
Agent
| boolean
| undefined
optional
auth:
string
| null
| undefined
optional
createConnection: ((
options: ClientRequestArgs,
oncreate: (
err: Error | null,
socket: stream.Duplex,
) => void
,
) =>
stream.Duplex
| null
| undefined
) | undefined
optional
defaultPort:
number
| string
| undefined
optional
family: number | undefined
optional
headers: OutgoingHttpHeaders | undefined
optional
hints: LookupOptions["hints"]
optional
host:
string
| null
| undefined
optional
hostname:
string
| null
| undefined
optional
insecureHTTPParser: boolean | undefined
optional
localAddress: string | undefined
optional
localPort: number | undefined
optional
lookup: LookupFunction | undefined
optional
maxHeaderSize: number | undefined
optional
method: string | undefined
optional
path:
string
| null
| undefined
optional
port:
number
| string
| null
| undefined
optional
protocol:
string
| null
| undefined
optional
setDefaultHeaders: boolean | undefined
optional
setHost: boolean | undefined
optional
signal: AbortSignal | undefined
optional
socketPath: string | undefined
optional
timeout: number | undefined
optional

Timeout in milliseconds.

uniqueHeaders: Array<string | string[]> | undefined
optional
joinDuplicateHeaders: boolean
optional

interface IncomingHttpHeaders

extends [NodeJS.Dict]<string | string[]>

Usage in Deno

import { type IncomingHttpHeaders } from "node:http";

Properties

accept: string | undefined
optional
accept-language: string | undefined
optional
accept-patch: string | undefined
optional
accept-ranges: string | undefined
optional
access-control-allow-credentials: string | undefined
optional
access-control-allow-headers: string | undefined
optional
access-control-allow-methods: string | undefined
optional
access-control-allow-origin: string | undefined
optional
access-control-expose-headers: string | undefined
optional
access-control-max-age: string | undefined
optional
access-control-request-headers: string | undefined
optional
access-control-request-method: string | undefined
optional
age: string | undefined
optional
allow: string | undefined
optional
alt-svc: string | undefined
optional
authorization: string | undefined
optional
cache-control: string | undefined
optional
connection: string | undefined
optional
content-disposition: string | undefined
optional
content-encoding: string | undefined
optional
content-language: string | undefined
optional
content-length: string | undefined
optional
content-location: string | undefined
optional
content-range: string | undefined
optional
content-type: string | undefined
optional
cookie: string | undefined
optional
date: string | undefined
optional
etag: string | undefined
optional
expect: string | undefined
optional
expires: string | undefined
optional
forwarded: string | undefined
optional
from: string | undefined
optional
host: string | undefined
optional
if-match: string | undefined
optional
if-modified-since: string | undefined
optional
if-none-match: string | undefined
optional
if-unmodified-since: string | undefined
optional
last-modified: string | undefined
optional
location: string | undefined
optional
origin: string | undefined
optional
pragma: string | undefined
optional
proxy-authenticate: string | undefined
optional
proxy-authorization: string | undefined
optional
public-key-pins: string | undefined
optional
range: string | undefined
optional
referer: string | undefined
optional
retry-after: string | undefined
optional
sec-websocket-accept: string | undefined
optional
sec-websocket-extensions: string | undefined
optional
sec-websocket-key: string | undefined
optional
sec-websocket-protocol: string | undefined
optional
sec-websocket-version: string | undefined
optional
set-cookie: string[] | undefined
optional
strict-transport-security: string | undefined
optional
tk: string | undefined
optional
trailer: string | undefined
optional
transfer-encoding: string | undefined
optional
upgrade: string | undefined
optional
user-agent: string | undefined
optional
vary: string | undefined
optional
via: string | undefined
optional
warning: string | undefined
optional
www-authenticate: string | undefined
optional

interface InformationEvent

Usage in Deno

import { type InformationEvent } from "node:http";

Properties

statusCode: number
statusMessage: string
httpVersion: string
httpVersionMajor: number
httpVersionMinor: number
headers: IncomingHttpHeaders
rawHeaders: string[]

interface OutgoingHttpHeaders

extends [NodeJS.Dict]<OutgoingHttpHeader>

Usage in Deno

import { type OutgoingHttpHeaders } from "node:http";

Properties

accept:
string
| string[]
| undefined
optional
accept-charset:
string
| string[]
| undefined
optional
accept-encoding:
string
| string[]
| undefined
optional
accept-language:
string
| string[]
| undefined
optional
accept-ranges: string | undefined
optional
access-control-allow-credentials: string | undefined
optional
access-control-allow-headers: string | undefined
optional
access-control-allow-methods: string | undefined
optional
access-control-allow-origin: string | undefined
optional
access-control-expose-headers: string | undefined
optional
access-control-max-age: string | undefined
optional
access-control-request-headers: string | undefined
optional
access-control-request-method: string | undefined
optional
age: string | undefined
optional
allow: string | undefined
optional
authorization: string | undefined
optional
cache-control: string | undefined
optional
cdn-cache-control: string | undefined
optional
connection:
string
| string[]
| undefined
optional
content-disposition: string | undefined
optional
content-encoding: string | undefined
optional
content-language: string | undefined
optional
content-length:
string
| number
| undefined
optional
content-location: string | undefined
optional
content-range: string | undefined
optional
content-security-policy: string | undefined
optional
content-security-policy-report-only: string | undefined
optional
content-type: string | undefined
optional
cookie:
string
| string[]
| undefined
optional
dav:
string
| string[]
| undefined
optional
dnt: string | undefined
optional
date: string | undefined
optional
etag: string | undefined
optional
expect: string | undefined
optional
expires: string | undefined
optional
forwarded: string | undefined
optional
from: string | undefined
optional
host: string | undefined
optional
if-match: string | undefined
optional
if-modified-since: string | undefined
optional
if-none-match: string | undefined
optional
if-range: string | undefined
optional
if-unmodified-since: string | undefined
optional
last-modified: string | undefined
optional
link:
string
| string[]
| undefined
optional
location: string | undefined
optional
max-forwards: string | undefined
optional
origin: string | undefined
optional
pragma:
string
| string[]
| undefined
optional
proxy-authenticate:
string
| string[]
| undefined
optional
proxy-authorization: string | undefined
optional
public-key-pins: string | undefined
optional
public-key-pins-report-only: string | undefined
optional
range: string | undefined
optional
referer: string | undefined
optional
referrer-policy: string | undefined
optional
refresh: string | undefined
optional
retry-after: string | undefined
optional
sec-websocket-accept: string | undefined
optional
sec-websocket-extensions:
string
| string[]
| undefined
optional
sec-websocket-key: string | undefined
optional
sec-websocket-protocol:
string
| string[]
| undefined
optional
sec-websocket-version: string | undefined
optional
server: string | undefined
optional
set-cookie:
string
| string[]
| undefined
optional
strict-transport-security: string | undefined
optional
te: string | undefined
optional
trailer: string | undefined
optional
transfer-encoding: string | undefined
optional
user-agent: string | undefined
optional
upgrade: string | undefined
optional
upgrade-insecure-requests: string | undefined
optional
vary: string | undefined
optional
via:
string
| string[]
| undefined
optional
warning: string | undefined
optional
www-authenticate:
string
| string[]
| undefined
optional
x-content-type-options: string | undefined
optional
x-dns-prefetch-control: string | undefined
optional
x-frame-options: string | undefined
optional
x-xss-protection: string | undefined
optional

interface RequestOptions

extends ClientRequestArgs

Usage in Deno

import { type RequestOptions } from "node:http";
Deno compatibility

Option createConnection is not supported.


interface ServerOptions

Usage in Deno

import { type ServerOptions } from "node:http";

Type Parameters

Request extends IncomingMessage = IncomingMessage
Response extends ServerResponse = ServerResponse

Properties

IncomingMessage: Request | undefined
optional

Specifies the IncomingMessage class to be used. Useful for extending the original IncomingMessage.

ServerResponse: Response | undefined
optional

Specifies the ServerResponse class to be used. Useful for extending the original ServerResponse.

requestTimeout: number | undefined
optional

Sets the timeout value in milliseconds for receiving the entire request from the client.

joinDuplicateHeaders: boolean
optional

It joins the field line values of multiple headers in a request with , instead of discarding the duplicates.

keepAliveTimeout: number | undefined
optional

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.

connectionsCheckingInterval: number | undefined
optional

Sets the interval value in milliseconds to check for request and headers timeout in incomplete requests.

highWaterMark: number | undefined
optional

Optionally overrides all sockets' readableHighWaterMark and writableHighWaterMark. This affects highWaterMark property of both IncomingMessage and ServerResponse. Default: @see stream.getDefaultHighWaterMark().

insecureHTTPParser: boolean | undefined
optional

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.

maxHeaderSize: number | undefined
optional

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.

noDelay: boolean | undefined
optional

If set to true, it disables the use of Nagle's algorithm immediately after a new incoming connection is received.

keepAlive: boolean | undefined
optional

If set to true, 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]).

keepAliveInitialDelay: number | undefined
optional

If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket.

uniqueHeaders: Array<string | string[]> | undefined
optional

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 ; .


type alias OutgoingHttpHeader

Usage in Deno

import { type OutgoingHttpHeader } from "node:http";

Definition

number
| string
| string[]

type alias RequestListener

Usage in Deno

import { type RequestListener } from "node:http";

Type Parameters

Request extends IncomingMessage = IncomingMessage
Response extends ServerResponse = ServerResponse

Definition

(
req: InstanceType<Request>,
res: InstanceType<Response> & { req: InstanceType<Request>; },
) => void

variable CloseEvent

Usage in Deno

import { CloseEvent } from "node:http";

Type

import("undici-types").CloseEvent

variable globalAgent

Usage in Deno

import { globalAgent } from "node:http";

Global instance of Agent which is used as the default for all HTTP client requests. Diverges from a default Agent configuration by having keepAlive enabled and a timeout of 5 seconds.

Type

Agent

variable maxHeaderSize

Usage in Deno

import { maxHeaderSize } from "node:http";

Read-only property specifying the maximum allowed size of HTTP headers in bytes. Defaults to 16KB. Configurable using the --max-http-header-size CLI option.

Type

number

variable MessageEvent

Usage in Deno

import { MessageEvent } from "node:http";

Type

import("undici-types").MessageEvent

variable METHODS

Usage in Deno

import { METHODS } from "node:http";

Type

string[]

variable STATUS_CODES

Usage in Deno

import { STATUS_CODES } from "node:http";

Index Signatures

[errorCode: number]: string | undefined
[errorCode: string]: string | undefined

variable WebSocket

Usage in Deno

import { WebSocket } from "node:http";

A browser-compatible implementation of WebSocket.

Type

import("undici-types").WebSocket

© 2018–2025 the Deno authors
Licensed under the MIT License.
https://docs.deno.com/api/node/http

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API