Exports
[<Class>]
type Exports =
static member CloseEvent: CloseEventConstructor
static member METHODS: string array
static member MessageEvent: MessageEventConstructor
static member STATUS_CODES: STATUSCODES
static member WebSocket: WebSocketConstructor
static member globalAgent: Agent
static member maxHeaderSize: float
static member Agent (?opts: AgentOptions) : Agent
static member ClientRequest (url: U3<string,ClientRequestArgs,URL>, ?cb: (IncomingMessage -> unit)) : ClientRequest
static member IncomingMessage (socket: Socket) : IncomingMessage
static member OutgoingMessage<'Request when 'Request :> IncomingMessage> () : OutgoingMessage<'Request>
static member Server<'Request, 'Response when 'Request :> IncomingMessageConstructor> (options: ServerOptions<'Request,'Response>, ?requestListener: Action<IncomingMessage,obj>) : Server<'Request,'Response>
static member Server<'Request, 'Response when 'Request :> IncomingMessageConstructor> (?requestListener: Action<IncomingMessage,obj>) : Server<'Request,'Response>
static member ServerResponse<'Request when 'Request :> IncomingMessage> (req: 'Request) : ServerResponse<'Request>
static member createServer<'Request, 'Response when 'Request :> IncomingMessageConstructor> (options: ServerOptions<'Request,'Response>, ?requestListener: Action<IncomingMessage,obj>) : Server<'Request,'Response>
static member createServer<'Request, 'Response when 'Request :> IncomingMessageConstructor> (?requestListener: Action<IncomingMessage,obj>) : Server<'Request,'Response>
static member get (url: U2<string,URL>, options: RequestOptions, ?callback: (IncomingMessage -> unit)) : ClientRequest
static member get (options: U3<string,RequestOptions,URL>, ?callback: (IncomingMessage -> unit)) : ClientRequest
static member request (url: U2<string,URL>, options: RequestOptions, ?callback: (IncomingMessage -> unit)) : ClientRequest
static member request (options: U3<string,RequestOptions,URL>, ?callback: (IncomingMessage -> unit)) : ClientRequest
static member setMaxIdleHTTPParsers (max: float) : unit
static member validateHeaderName (name: string) : unit
static member validateHeaderValue (name: string, value: string) : unit| Assembly | Xantham.Fable.Node |
| Attributes | [<Erase>] |
The package's value exports, each bound to its import.
Properties
static member STATUS_CODES: STATUSCODESstatic member WebSocket: WebSocketConstructor
static member WebSocket: WebSocketConstructorA browser-compatible implementation of WebSocket.
@since v22.5.0
static member globalAgent: Agent
static member globalAgent: AgentGlobal 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.
@since v0.5.9
static member maxHeaderSize: float
static member maxHeaderSize: floatRead-only property specifying the maximum allowed size of HTTP headers in bytes. Defaults to 16KB. Configurable using the --max-http-header-size CLI option.
Methods
static member Agent (?opts: AgentOptions) : Agent
static member Agent (?opts: AgentOptions) : AgentAn 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)
@since v0.3.4
static member ClientRequest (url: U3<string,ClientRequestArgs,URL>, ?cb: (IncomingMessage -> unit)) : ClientRequest
static member ClientRequest (url: U3<string,ClientRequestArgs,URL>, ?cb: (IncomingMessage -> unit)) : ClientRequestThis 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.
@since v0.1.17
static member IncomingMessage (socket: Socket) : IncomingMessage
static member IncomingMessage (socket: Socket) : IncomingMessageAn 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.
@since v0.1.17
static member OutgoingMessage<'Request when 'Request :> IncomingMessage> () : OutgoingMessage<'Request>
static member OutgoingMessage<'Request when 'Request :> IncomingMessage> () : OutgoingMessage<'Request>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.
@since v0.1.17
static member Server<'Request, 'Response when 'Request :> IncomingMessageConstructor> (options: ServerOptions<'Request,'Response>, ?requestListener: Action<IncomingMessage,obj>) : Server<'Request,'Response>
static member Server<'Request, 'Response when 'Request :> IncomingMessageConstructor> (options: ServerOptions<'Request,'Response>, ?requestListener: Action<IncomingMessage,obj>) : Server<'Request,'Response>@since v0.1.17
static member Server<'Request, 'Response when 'Request :> IncomingMessageConstructor> (?requestListener: Action<IncomingMessage,obj>) : Server<'Request,'Response>
static member Server<'Request, 'Response when 'Request :> IncomingMessageConstructor> (?requestListener: Action<IncomingMessage,obj>) : Server<'Request,'Response>@since v0.1.17
static member ServerResponse<'Request when 'Request :> IncomingMessage> (req: 'Request) : ServerResponse<'Request>
static member ServerResponse<'Request when 'Request :> IncomingMessage> (req: 'Request) : ServerResponse<'Request>This object is created internally by an HTTP server, not by the user. It is passed as the second parameter to the 'request' event.
@since v0.1.17
static member createServer<'Request, 'Response when 'Request :> IncomingMessageConstructor> (options: ServerOptions<'Request,'Response>, ?requestListener: Action<IncomingMessage,obj>) : Server<'Request,'Response>
static member createServer<'Request, 'Response when 'Request :> IncomingMessageConstructor> (options: ServerOptions<'Request,'Response>, ?requestListener: Action<IncomingMessage,obj>) : 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);
@since v0.1.13
static member createServer<'Request, 'Response when 'Request :> IncomingMessageConstructor> (?requestListener: Action<IncomingMessage,obj>) : Server<'Request,'Response>
static member createServer<'Request, 'Response when 'Request :> IncomingMessageConstructor> (?requestListener: Action<IncomingMessage,obj>) : 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);
@since v0.1.13
static member get (url: U2<string,URL>, options: RequestOptions, ?callback: (IncomingMessage -> unit)) : ClientRequest
static member get (url: U2<string,URL>, options: RequestOptions, ?callback: (IncomingMessage -> unit)) : ClientRequestSince 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);
@since v0.3.6
| Parameter | |
|---|---|
options | Accepts the same options as {@link request}, with the method set to GET by default. |
static member get (options: U3<string,RequestOptions,URL>, ?callback: (IncomingMessage -> unit)) : ClientRequest
static member get (options: U3<string,RequestOptions,URL>, ?callback: (IncomingMessage -> unit)) : ClientRequestSince 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);
@since v0.3.6
| Parameter | |
|---|---|
options | Accepts the same options as {@link request}, with the method set to GET by default. |
static member request (url: U2<string,URL>, options: RequestOptions, ?callback: (IncomingMessage -> unit)) : ClientRequest
static member request (url: U2<string,URL>, options: RequestOptions, ?callback: (IncomingMessage -> unit)) : ClientRequestoptions 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
authoption 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 theresobject ('data'will not be emitted at all if the response body is empty, for instance, in most redirects)'end'on theresobject'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 theresobject- (connection closed here)
'aborted'on theresobject'close''error'on theresobject with an error with message'Error: aborted'and code'ECONNRESET''close'on theresobject
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 whichreq.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 whichreq.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 theresobject- (
req.destroy()called here) 'aborted'on theresobject'close''error'on theresobject with an error with message'Error: aborted'and code'ECONNRESET', or the error with whichreq.destroy()was called'close'on theresobject
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 theresobject- (
req.abort()called here) 'abort''aborted'on theresobject'error'on theresobject with an error with message'Error: aborted'and code'ECONNRESET'.'close''close'on theresobject
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.
@since v0.3.6
static member request (options: U3<string,RequestOptions,URL>, ?callback: (IncomingMessage -> unit)) : ClientRequest
static member request (options: U3<string,RequestOptions,URL>, ?callback: (IncomingMessage -> unit)) : ClientRequestoptions 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
authoption 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 theresobject ('data'will not be emitted at all if the response body is empty, for instance, in most redirects)'end'on theresobject'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 theresobject- (connection closed here)
'aborted'on theresobject'close''error'on theresobject with an error with message'Error: aborted'and code'ECONNRESET''close'on theresobject
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 whichreq.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 whichreq.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 theresobject- (
req.destroy()called here) 'aborted'on theresobject'close''error'on theresobject with an error with message'Error: aborted'and code'ECONNRESET', or the error with whichreq.destroy()was called'close'on theresobject
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 theresobject- (
req.abort()called here) 'abort''aborted'on theresobject'error'on theresobject with an error with message'Error: aborted'and code'ECONNRESET'.'close''close'on theresobject
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.
@since v0.3.6
static member setMaxIdleHTTPParsers (max: float) : unit
static member setMaxIdleHTTPParsers (max: float) : unitSet the maximum number of idle HTTP parsers.
@since v18.8.0, v16.18.0
static member validateHeaderName (name: string) : unit
static member validateHeaderName (name: string) : unitPerforms 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 [""]'
}
@since v14.3.0
| Parameter | |
|---|---|
label | Label for error message. |
static member validateHeaderValue (name: string, value: string) : unit
static member validateHeaderValue (name: string, value: string) : unitPerforms 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"]'
}
@since v14.3.0
| Parameter | |
|---|---|
name | Header name |
value | Header value |