知识共享许可协议
本作品采用知识共享署名-非商业性使用 3.0 未本地化版本许可协议进行许可。

Node.js v0.10.18 手册 & 文档


目录

HTTP#

稳定度: 3 - 稳定

To use the HTTP server and client one must require('http').

要使用HTTP服务或客户端功能,需引用此模块require('http').

The HTTP interfaces in Node 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--the user is able to stream data.

Node中的HTTP接口的设计支持许多这个协议中原本用起来很困难的特性.特别是对于很大的或者块编码的消息.这些接口很谨慎,它从来不会完全缓存整个请求(request)或响应(response),这样用户可以在请求(request)或响应(response)中使用数据流.

HTTP message headers are represented by an object like this:

HTTP 的消息头(Headers)通过如下对象来表示:

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

Keys are lowercased. Values are not modified.

其中键为小写字母,值是不能修改的。

In order to support the full spectrum of possible HTTP applications, Node's 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.

为了能更加全面地支持HTTP应用,Node的HTTP API是很接近底层,它是可以处理数据流还有只转化消息。它把一个消息写到报文头和报文体,但是它并没有解析报文头或报文体。

Defined headers that allow multiple values are concatenated with a , character, except for the set-cookie and cookie headers which are represented as an array of values. Headers such as content-length which can only have a single value are parsed accordingly, and only a single value is represented on the parsed object.

定义好的消息头允许多个值以,分割, 除了set-cookiecookie,因为他们表示值的数组. 消息头,比如 content-length只能有单个值, 并且单个值表示解析好的对象.

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:

接收到的原始头信息以数组形式 [key, value, key2, value2, ...] 保存在 rawHeaders 属性中. 例如, 前面提到的消息对象会有 rawHeaders 列表如下:

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

http.STATUS_CODES#

  • Object

  • Object

A collection of all the standard HTTP response status codes, and the short description of each. For example, http.STATUS_CODES[404] === 'Not Found'.

所以标准HTTP响应码的集合,以及每个响应码的简短描述.例如:http.STATUS_CODES[404]==='Not Found'.

http.createServer([requestListener])#

Returns a new web server object.

返回一个新的web服务器对象

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

参数 requestListener 是一个函数,它将会自动加入到 'request' 事件的监听队列.

http.createClient([port], [host])#

This function is deprecated; please use http.request() instead. Constructs a new HTTP client. port and host refer to the server to be connected to.

该函数已弃用,请用http.request()代替. 创建一个新的HTTP客户端. porthost 表示所连接的服务器.

Class: http.Server#

This is an EventEmitter with the following events:

这是一个包含下列事件的EventEmitter:

Event: 'request'#

function (request, response) { }

function (request, response) { }

Emitted each time there is a request. Note that there may be multiple requests per connection (in the case of keep-alive connections). request is an instance of http.IncomingMessage and response is an instance of http.ServerResponse

每次收到一个请求时触发.注意每个连接又可能有多个请求(在keep-alive的连接中).requesthttp.IncomingMessage的一个实例.responsehttp.ServerResponse的一个实例

事件: 'connection'#

function (socket) { }

function (socket) { }

When a new TCP stream is established. socket is an object of type net.Socket. Usually users will not want to access this event. In particular, the socket will not emit readable events because of how the protocol parser attaches to the socket. The socket can also be accessed at request.connection.

新的TCP流建立时出发。 socket是一个net.Socket对象。 通常用户无需处理该事件。 特别注意,协议解析器绑定套接字时采用的方式使套接字不会出发readable事件。 还可以通过request.connection访问socket

事件: 'close'#

function () { }

function () { }

Emitted when the server closes.

当此服务器关闭时触发

Event: 'checkContinue'#

function (request, response) { }

function (request, response) { }

Emitted each time a request with an http Expect: 100-continue is received. If this event isn't listened for, the server will automatically respond with a 100 Continue as appropriate.

每当收到Expect: 100-continue的http请求时触发。 如果未监听该事件,服务器会酌情自动发送100 Continue响应。

Handling this event involves calling response.writeContinue if the client should continue to send the request body, or generating an appropriate HTTP response (e.g., 400 Bad Request) if the client should not continue to send the request body.

处理该事件时,如果客户端可以继续发送请求主体则调用response.writeContinue, 如果不能则生成合适的HTTP响应(例如,400 请求无效)。

Note that when this event is emitted and handled, the request event will not be emitted.

需要注意到, 当这个事件触发并且被处理后, request 时间将不再会触发.

事件: 'connect'#

function (request, socket, head) { }

function (request, socket, head) { }

Emitted each time a client requests a http CONNECT method. If this event isn't listened for, then clients requesting a CONNECT method will have their connections closed.

每当客户端发起CONNECT请求时出发。如果未监听该事件,客户端发起CONNECT请求时连接会被关闭。

  • request is the arguments for the http request, as it is in the request event.
  • socket is the network socket between the server and client.
  • head is an instance of Buffer, the first packet of the tunneling stream, this may be empty.

  • request 是该HTTP请求的参数,与request事件中的相同。

  • socket 是服务端与客户端之间的网络套接字。
  • head 是一个Buffer实例,隧道流的第一个包,该参数可能为空。

After this event is emitted, the request's socket will not have a data event listener, meaning you will need to bind to it in order to handle data sent to the server on that socket.

在这个事件被分发后,请求的套接字将不会有data事件监听器,也就是说你将需要绑定一个监听器到data事件,来处理在套接字上被发送到服务器的数据。

Event: 'upgrade'#

function (request, socket, head) { }

function (request, socket, head) { }

Emitted each time a client requests a http upgrade. If this event isn't listened for, then clients requesting an upgrade will have their connections closed.

每当一个客户端请求http升级时,该事件被分发。如果这个事件没有被监听,那么这些请求升级的客户端的连接将会被关闭。

  • request is the arguments for the http request, as it is in the request event.
  • socket is the network socket between the server and client.
  • head is an instance of Buffer, the first packet of the upgraded stream, this may be empty.

  • request 是该HTTP请求的参数,与request事件中的相同。

  • socket 是服务端与客户端之间的网络套接字。
  • head 是一个Buffer实例,升级后流的第一个包,该参数可能为空。

After this event is emitted, the request's socket will not have a data event listener, meaning you will need to bind to it in order to handle data sent to the server on that socket.

在这个事件被分发后,请求的套接字将不会有data事件监听器,也就是说你将需要绑定一个监听器到data事件,来处理在套接字上被发送到服务器的数据。

Event: 'clientError'#

function (exception, socket) { }

function (exception, socket) { }

If a client connection emits an 'error' event - it will forwarded here.

如果一个客户端连接触发了一个 'error' 事件, 它就会转发到这里.

socket is the net.Socket object that the error originated from.

socket 是导致错误的 net.Socket 对象。

server.listen(port, [hostname], [backlog], [callback])#

Begin accepting connections on the specified port and hostname. If the hostname is omitted, the server will accept connections directed to any IPv4 address (INADDR_ANY).

开始在指定的主机名和端口接收连接。如果省略主机名,服务器会接收指向任意IPv4地址的链接(INADDR_ANY)。

To listen to a unix socket, supply a filename instead of port and hostname.

监听一个 unix socket, 需要提供一个文件名而不是端口号和主机名。

Backlog is the maximum length of the queue of pending connections. The actual length will be determined by your OS through sysctl settings such as tcp_max_syn_backlog and somaxconn on linux. The default value of this parameter is 511 (not 512).

积压量 backlog 为连接等待队列的最大长度。实际长度由您的操作系统通过 sysctl 设置决定,比如 Linux 上的 tcp_max_syn_backlogsomaxconn。该参数缺省值为 511(不是 512)。

This function is asynchronous. The last parameter callback will be added as a listener for the 'listening' event. See also net.Server.listen(port).

这个函数是异步的。最后一个参数callback会被作为事件监听器添加到 'listening'事件。另见net.Server.listen(port)

server.listen(path, [callback])#

Start a UNIX socket server listening for connections on the given path.

启动一个 UNIX 套接字服务器在所给路径 path 上监听连接。

This function is asynchronous. The last parameter callback will be added as a listener for the 'listening' event. See also net.Server.listen(path).

该函数是异步的.最后一个参数callback将会加入到[listening][]事件的监听队列中.又见net.Server.listen(path).

server.listen(handle, [callback])#

  • handle Object
  • callback Function

  • handle处理器 Object

  • callback回调函数 Function

The handle object can be set to either a server or socket (anything with an underlying _handle member), or a {fd: <n>} object.

handle 变量可以被设置为server 或者 socket(任一以下划线开头的成员 _handle), 或者一个 {fd: <n>} 对象

This will cause the server to accept connections on the specified handle, but it is presumed that the file descriptor or handle has already been bound to a port or domain socket.

这将使服务器用指定的句柄接受连接,但它假设文件描述符或者句柄已经被绑定在特定的端口或者域名套接字。

Listening on a file descriptor is not supported on Windows.

Windows 不支持监听一个文件描述符。

This function is asynchronous. The last parameter callback will be added as a listener for the 'listening' event. See also net.Server.listen().

这个函数是异步的。最后一个参数callback会被作为事件监听器添加到'listening'事件。另见net.Server.listen()

server.close([callback])#

Stops the server from accepting new connections. See net.Server.close().

禁止服务端接收新的连接. 查看 net.Server.close().

server.maxHeadersCount#

Limits maximum incoming headers count, equal to 1000 by default. If set to 0 - no limit will be applied.

最大请求头数目限制, 默认 1000 个. 如果设置为0, 则代表不做任何限制.

server.setTimeout(msecs, callback)#

  • msecs Number
  • callback Function

  • msecs Number

  • callback Function

Sets the timeout value for sockets, and emits a 'timeout' event on the Server object, passing the socket as an argument, if a timeout occurs.

为套接字设定超时值。如果一个超时发生,那么Server对象上会分发一个'timeout'事件,同时将套接字作为参数传递。

If there is a 'timeout' event listener on the Server object, then it will be called with the timed-out socket as an argument.

如果在Server对象上有一个'timeout'事件监听器,那么它将被调用,而超时的套接字会作为参数传递给这个监听器。

By default, the Server's timeout value is 2 minutes, and sockets are destroyed automatically if they time out. However, if you assign a callback to the Server's 'timeout' event, then you are responsible for handling socket timeouts.

默认情况下,服务器的超时时间是2分钟,超时后套接字会自动销毁。 但是如果为‘timeout’事件指定了回调函数,你需要负责处理套接字超时。

server.timeout#

  • Number Default = 120000 (2 minutes)

  • Number 默认 120000 (2 分钟)

The number of milliseconds of inactivity before a socket is presumed to have timed out.

一个套接字被判断为超时之前的闲置毫秒数。

Note that the socket timeout logic is set up on connection, so changing this value only affects new connections to the server, not any existing connections.

注意套接字的超时逻辑在连接时被设定,所以更改这个值只会影响新创建的连接,而不会影响到现有连接。

Set to 0 to disable any kind of automatic timeout behavior on incoming connections.

设置为0将阻止之后建立的连接的一切自动超时行为。

Class: http.ServerResponse#

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

The response implements the Writable Stream interface. This is an EventEmitter with the following events:

事件: 'close'#

function () { }

function () { }

Indicates that the underlying connection was terminated before response.end() was called or able to flush.

response.writeContinue()#

Sends a HTTP/1.1 100 Continue message to the client, indicating that the request body should be sent. See the 'checkContinue' event on Server.

response.writeHead(statusCode, [reasonPhrase], [headers])#

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 reasonPhrase as the second argument.

向请求回复响应头. statusCode是一个三位是的HTTP状态码, 例如 404. 最后一个参数, headers, 是响应头的内容. 可以选择性的,把人类可读的‘原因短句’作为第二个参数。

Example:

示例:

var body = 'hello world';
response.writeHead(200, {
  'Content-Length': body.length,
  'Content-Type': 'text/plain' });

This method must only be called once on a message and it must be called before response.end() is called.

这个方法只能在消息到来后使用一次 而且这必须在response.end() 之后调用。

If you call response.write() or response.end() before calling this, the implicit/mutable headers will be calculated and call this function for you.

如果你在调用这之前调用了response.write()或者 response.end() , 就会调用这个函数,并且 不明/容易混淆 的头将会被使用。

Note: that Content-Length is given in bytes not characters. The above example works because the string 'hello world' contains only single byte characters. If the body contains higher coded characters then Buffer.byteLength() should be used to determine the number of bytes in a given encoding. And Node does not check whether Content-Length and the length of the body which has been transmitted are equal or not.

注意:Content-Length 是以字节(byte)计,而不是以字符(character)计。之前的例子奏效的原因是字符串'hello world'只包含了单字节的字符。如果body包含了多字节编码的字符,就应当使用Buffer.byteLength()来确定在多字节字符编码情况下字符串的字节数。需要进一步说明的是Node不检查Content-Lenth属性和已传输的body长度是否吻合。

response.setTimeout(msecs, callback)#

  • msecs Number
  • callback Function

  • msecs Number

  • callback Function

Sets the Socket's timeout value to msecs. If a callback is provided, then it is added as a listener on the 'timeout' event on the response object.

设定套接字的超时时间为msecs。如果提供了回调函数,会将其添加为响应对象的'timeout'事件的监听器。

If no 'timeout' listener is added to the request, the response, or the server, then sockets are destroyed when they time out. If you assign a handler on the request, the response, or the server's 'timeout' events, then it is your responsibility to handle timed out sockets.

如果请求、响应、服务器均未添加'timeout'事件监听,套接字将在超时时被销毁。 如果监听了请求、响应、服务器之一的'timeout'事件,需要自行处理超时的套接字。

response.statusCode#

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.

Example:

示例:

response.statusCode = 404;

After response header was sent to the client, this property indicates the status code which was sent out.

response.setHeader(name, value)#

Sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings here if you need to send multiple headers with the same name.

为默认或者已存在的头设置一条单独的头内容。如果这个头已经存在于 将被送出的头中,将会覆盖原来的内容。如果我想设置更多的头, 就使用一个相同名字的字符串数组

Example:

示例:

response.setHeader("Content-Type", "text/html");

or

或者

response.setHeader("Set-Cookie", ["type=ninja", "language=javascript"]);

response.headersSent#

Boolean (read-only). True if headers were sent, false otherwise.

Boolean值(只读).如果headers发送完毕,则为true,反之为false

response.sendDate#

When true, the Date header will be automatically generated and sent in the response if it is not already present in the headers. Defaults to true.

若为true,则当headers里没有Date值时自动生成Date并发送.默认值为true

This should only be disabled for testing; HTTP requires the Date header in responses.

只有在测试环境才禁用它; 因为 HTTP 要求响应包含 Date 头.

response.getHeader(name)#

Reads out a header that's already been queued but not sent to the client. Note that the name is case insensitive. This can only be called before headers get implicitly flushed.

Example:

示例:

var contentType = response.getHeader('content-type');

response.removeHeader(name)#

Removes a header that's queued for implicit sending.

Example:

示例:

response.removeHeader("Content-Encoding");

response.write(chunk, [encoding])#

If this method is called and response.writeHead() has not been called, it will switch to implicit header mode and flush the implicit headers.

This sends a chunk of the response body. This method may be called multiple times to provide successive parts of the body.

chunk can be a string or a buffer. If chunk is a string, the second parameter specifies how to encode it into a byte stream. By default the encoding is 'utf8'.

Note: This is the raw HTTP body and has nothing to do with higher-level multi-part body encodings that may be used.

The first time response.write() is called, it will send the buffered header information and the first body to the client. The second time response.write() is called, Node assumes you're going to be streaming data, and sends that separately. That is, the response is buffered up to the first chunk of body.

Returns true if the entire data was flushed successfully to the kernel buffer. Returns false if all or part of the data was queued in user memory. 'drain' will be emitted when the buffer is again free.

如果所有数据被成功刷新到内核缓冲区,则返回true。如果所有或部分数据在用户内存里还处于队列中,则返回false。当缓冲区再次被释放时,'drain'事件会被分发。 'drain' will be emitted when the buffer is again free.

response.addTrailers(headers)#

This method adds HTTP trailing headers (a header but at the end of the message) to the response.

Trailers will only be emitted if chunked encoding is used for the response; if it is not (e.g., if the request was HTTP/1.0), they will be silently discarded.

Note that HTTP requires the Trailer header to be sent if you intend to emit trailers, with a list of the header fields in its value. E.g.,

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

response.end([data], [encoding])#

This method signals to the server that all of the response headers and body have been sent; that server should consider this message complete. The method, response.end(), MUST be called on each response.

If data is specified, it is equivalent to calling response.write(data, encoding) followed by response.end().

http.request(options, callback)#

Node maintains several connections per server to make HTTP requests. This function allows one to transparently issue requests.

options can be an object or a string. If options is a string, it is automatically parsed with url.parse().

options 可以是一个对象或一个字符串。如果 options是一个字符串, 它将自动的使用url.parse()解析。

Options:

Options:

  • host: A domain name or IP address of the server to issue the request to. Defaults to 'localhost'.
  • hostname: To support url.parse() hostname is preferred over host
  • port: Port of remote server. Defaults to 80.
  • localAddress: Local interface to bind for network connections.
  • socketPath: Unix Domain Socket (use one of host:port or socketPath)
  • method: A string specifying the HTTP request method. Defaults to 'GET'.
  • path: Request path. Defaults to '/'. Should include query string if any. E.G. '/index.html?page=12'. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future.
  • headers: An object containing request headers.
  • auth: Basic authentication i.e. 'user:password' to compute an Authorization header.
  • agent: Controls Agent behavior. When an Agent is used request will default to Connection: keep-alive. Possible values:
    • undefined (default): use global Agent for this host and port.
    • Agent object: explicitly use the passed in Agent.
    • false: opts out of connection pooling with an Agent, defaults request to Connection: close.
  • keepAlive: {Boolean} Keep sockets around in a pool to be used by other requests in the future. Default = false
  • keepAliveMsecs: {Integer} 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.

  • host: 要发送请求的服务端域名或IP地址。 默认为'localhost'

  • hostname: 要支持url.parse()的话,优先使用hostname而不是host
  • port: 远程服务器的端口。默认为80。
  • localAddress: 本地接口,用来绑定网络连接。
  • socketPath: Unix Domain Socket (use one of host:port or socketPath)
  • method: A string specifying the HTTP request method. Defaults to 'GET'.
  • path: Request path. Defaults to '/'. Should include query string if any. E.G. '/index.html?page=12'. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future.
  • headers: An object containing request headers.
  • auth: Basic authentication i.e. 'user:password' to compute an Authorization header.
  • agent: Controls Agent behavior. When an Agent is used request will default to Connection: keep-alive. Possible values:
    • undefined (default): use global Agent for this host and port.
    • Agent object: explicitly use the passed in Agent.
    • false: opts out of connection pooling with an Agent, defaults request to Connection: close.
  • keepAlive: {Boolean} Keep sockets around in a pool to be used by other requests in the future. Default = false
  • keepAliveMsecs: {Integer} 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.

http.request() returns an instance of the http.ClientRequest class. The ClientRequest instance is a writable stream. If one needs to upload a file with a POST request, then write to the ClientRequest object.

http.request() 返回一个 http.ClientRequest类的实例。ClientRequest实例是一个可写流对象。如果需要用POST请求上传一个文件的话,就将其写入到ClientRequest对象。

Example:

示例:

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();

Note that in the example req.end() was called. With http.request() one must always call req.end() to signify that you're done with the request - even if there is no data being written to the request body.

注意,例子里的req.end()被调用了。使用http.request()方法时都必须总是调用req.end()以表明这个请求已经完成,即使响应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.

There are a few special headers that should be noted.

  • Sending a 'Connection: keep-alive' will notify Node that the connection to the server should be persisted until the next request.

  • Sending a 'Content-length' header will disable the default chunked encoding.

  • 发送 'Content-length' 头将会禁用默认的 chunked 编码.

  • Sending an 'Expect' header will immediately send the request headers. Usually, when sending 'Expect: 100-continue', you should both set a timeout and listen for the continue event. See RFC2616 Section 8.2.3 for more information.

  • Sending an Authorization header will override using the auth option to compute basic authentication.

http.get(options, callback)#

Since most requests are GET requests without bodies, Node provides this convenience method. The only difference between this method and http.request() is that it sets the method to GET and calls req.end() automatically.

Example:

示例:

http.get("http://www.google.com/index.html", function(res) {
  console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
  console.log("Got error: " + e.message);
});

Class: http.Agent#

The HTTP Agent is used for pooling sockets used in HTTP client requests.

The HTTP Agent also defaults client requests to using Connection:keep-alive. If no pending HTTP requests are waiting on a socket to become free the socket is closed. This means that Node's pool has the benefit of keep-alive when under load but still does not require developers to manually close the HTTP clients using KeepAlive.

If you opt into using HTTP KeepAlive, you can create an Agent object with that flag set to true. (See the constructor options below.) Then, the Agent will keep unused sockets in a pool for later use. They will be explicitly marked so as to not keep the Node process running. However, it is still a good idea to explicitly destroy() KeepAlive agents when they are no longer in use, so that the Sockets will be shut down.

Sockets are removed from the agent's pool when the socket emits either a "close" event or a special "agentRemove" event. This means that if you intend to keep one HTTP request open for a long time and don't want it to stay in the pool you can do something along the lines of:

http.get(options, function(res) {
  // Do stuff
}).on("socket", function (socket) {
  socket.emit("agentRemove");
});

Alternatively, you could just opt out of pooling entirely using agent:false:

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

new Agent([options])#

  • options Object Set of configurable options to set on the agent. Can have the following fields:
    • keepAlive Boolean Keep sockets around in a pool to be used by other requests in the future. Default = false
    • keepAliveMsecs Integer 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 Maximum number of sockets to allow per host. Default = Infinity.
    • maxFreeSockets Number Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256.

The default http.globalAgent that is used by http.request has all of these values set to their respective defaults.

To configure any of them, you must create your own Agent object.

要配置这些值,你必须创建一个你自己的Agent对象。

var http = require('http');
var keepAliveAgent = new http.Agent({ keepAlive: true });
keepAliveAgent.request(options, onResponseCallback);

agent.maxSockets#

By default set to Infinity. Determines how many concurrent sockets the agent can have open per host.

agent.maxFreeSockets#

By default set to 256. For Agents supporting HTTP KeepAlive, this sets the maximum number of sockets that will be left open in the free state.

agent.sockets#

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

agent.freeSockets#

An object which contains arrays of sockets currently awaiting use by the Agent when HTTP KeepAlive is used. Do not modify.

agent.requests#

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

agent.destroy()#

Destroy any sockets that are currently in use by the agent.

销毁被此 agent 正在使用着的所有 sockets.

It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, sockets may hang open for quite a long time before the server terminates them.

agent.getName(options)#

Get a unique name for a set of request options, to determine whether a connection can be reused. In the http agent, this returns host:port:localAddress. In the https agent, the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options that determine socket reusability.

http.globalAgent#

Global instance of Agent which is used as the default for all http client requests.

Class: http.ClientRequest#

This object is created internally and returned from http.request(). It represents an in-progress request whose header has already been queued. The header is still mutable using the setHeader(name, value), getHeader(name), removeHeader(name) API. The actual header will be sent along with the first data chunk or when closing the connection.

To get the response, add a listener for 'response' to the request object. 'response' will be emitted from the request object when the response headers have been received. The 'response' event is executed with one argument which is an instance of http.IncomingMessage.

During the 'response' event, one can add listeners to the response object; particularly to listen for the 'data' event.

If no 'response' handler is added, then the response will be entirely discarded. However, if you add a 'response' event handler, then you must consume the data from the response object, 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.

Note: Node does not check whether Content-Length and the length of the body which has been transmitted are equal or not.

The request implements the Writable Stream interface. This is an EventEmitter with the following events:

Event 'response'#

function (response) { }

function (response) { }

Emitted when a response is received to this request. This event is emitted only once. The response argument will be an instance of http.IncomingMessage.

Options:

Options:

  • host: A domain name or IP address of the server to issue the request to.
  • port: Port of remote server.
  • socketPath: Unix Domain Socket (use one of host:port or socketPath)

  • host: 请求要发送的域名或服务器的IP地址。

  • port: 远程服务器的端口。
  • socketPath: Unix Domain Socket (使用host:port或socketPath)

Event: 'socket'#

function (socket) { }

function (socket) { }

Emitted after a socket is assigned to this request.

当一个套接字被分配到这个请求之后,该事件被分发。

事件: 'connect'#

function (response, socket, head) { }

function (response, socket, head) { }

Emitted each time a server responds to a request with a CONNECT method. If this event isn't being listened for, clients receiving a CONNECT method will have their connections closed.

A client server pair that show you how to listen for the connect event.

    // make a request over an HTTP tunnel
    socket.write('GET / HTTP/1.1\r\n' +
                 'Host: www.google.com:80\r\n' +
                 'Connection: close\r\n' +
                 '\r\n');
    socket.on('data', function(chunk) {
      console.log(chunk.toString());
    });
    socket.on('end', function() {
      proxy.close();
    });
  });
});

Event: 'upgrade'#

function (response, socket, head) { }

function (response, socket, head) { }

Emitted each time a server responds to a request with an upgrade. If this event isn't being listened for, clients receiving an upgrade header will have their connections closed.

A client server pair that show you how to listen for the upgrade event.

  req.on('upgrade', function(res, socket, upgradeHead) {
    console.log('got upgraded!');
    socket.end();
    process.exit(0);
  });
});

Event: 'continue'#

function () { }

function () { }

Emitted when the server sends a '100 Continue' HTTP response, usually because the request contained 'Expect: 100-continue'. This is an instruction that the client should send the request body.

request.write(chunk, [encoding])#

Sends a chunk of the body. By calling this method many times, the user can stream a request body to a server--in that case it is suggested to use the ['Transfer-Encoding', 'chunked'] header line when creating the request.

The chunk argument should be a Buffer or a string.

chunk 参数必须是 Buffer 或者 string.

The encoding argument is optional and only applies when chunk is a string. Defaults to 'utf8'.

encoding 参数是可选的, 并且只能在 chunk 是 string 类型的时候才能设置. 默认是 'utf8'.

request.end([data], [encoding])#

Finishes sending the request. If any parts of the body are unsent, it will flush them to the stream. If the request is chunked, this will send the terminating '0\r\n\r\n'.

If data is specified, it is equivalent to calling request.write(data, encoding) followed by request.end().

request.abort()#

Aborts a request. (New since v0.3.8.)

终止一个请求. (从 v0.3.8 开始新加.)

request.setTimeout(timeout, [callback])#

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

request.setNoDelay([noDelay])#

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

request.setSocketKeepAlive([enable], [initialDelay])#

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

一旦一个套接字被分配到这个请求,而且成功连接,那么socket.setKeepAlive()就会被调用。

http.IncomingMessage#

An IncomingMessage object is created by http.Server or http.ClientRequest and passed as the first argument to the 'request' and 'response' event respectively. It may be used to access response status, headers and data.

一个 IncomingMessage对象是由 http.Serverhttp.ClientRequest创建的,并作为第一参数分别传递给'request''response' 事件。它也可以被用来访问应答的状态,头文件和数据。

It implements the Readable Stream interface, as well as the following additional events, methods, and properties.

这个实现了 [可读流][]接口以及以下增加的事件,函数和属性。

事件: 'close'#

function () { }

function () { }

Indicates that the underlaying connection was terminated before response.end() was called or able to flush.

表示在response.end()被调用或强制刷新之前,底层的连接已经被终止了。

Just like 'end', this event occurs only once per response. See [http.ServerResponse][]'s 'close' event for more information.

'end'一样,这个事件对于每个应答只会触发一次。详见[http.ServerResponse][]的 'close'事件。

message.httpVersion#

In case of server request, the HTTP version sent by the client. In the case of client response, the HTTP version of the connected-to server. Probably either '1.1' or '1.0'.

客户端向服务器发出请求时,客户端发送的HTTP版本;或是服务器向客户端返回应答时,服务器的HTTP版本。通常是 '1.1''1.0'

Also response.httpVersionMajor is the first integer and response.httpVersionMinor is the second.

message.headers#

The request/response headers object.

请求/响应 头对象.

Read only map of header names and values. Header names are lower-cased. Example:

只读的头文件名称和值的映射。头文件名称全小写。示例:

// 输出类似这样:
//
// { 'user-agent': 'curl/7.22.0',
//   host: '127.0.0.1:8000',
//   accept: '*/*' }
console.log(request.headers);

message.rawHeaders#

The raw request/response headers list exactly as they were received.

Note that the keys and values are in the same list. It is not a list of tuples. So, the even-numbered offsets are key values, and the odd-numbered offsets are the associated values.

Header names are not lowercased, and duplicates are not merged.

// Prints something like:
//
// [ 'user-agent',
//   'this is invalid because there can be only one',
//   'User-Agent',
//   'curl/7.22.0',
//   'Host',
//   '127.0.0.1:8000',
//   'ACCEPT',
//   '*/*' ]
console.log(request.rawHeaders);

message.trailers#

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

message.rawTrailers#

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

message.setTimeout(msecs, callback)#

  • msecs Number
  • callback Function

  • msecs Number

  • callback Function

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

调用message.connection.setTimeout(msecs, callback)

message.method#

Only valid for request obtained from http.Server.

仅对从http.Server获得到的请求(request)有效.

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

请求(request)方法如同一个只读的字符串,比如‘GET’、‘DELETE’。

message.url#

Only valid for request obtained from http.Server.

仅对从http.Server获得到的请求(request)有效.

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

请求的URL字符串.它仅包含实际HTTP请求中所提供的URL.加入请求如下:

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

Then request.url will be:

request.url 为:

'/status?name=ryan'

If you would like to parse the URL into its parts, you can use require('url').parse(request.url). Example:

如果你想要将URL分解出来,你可以用require('url').parse(request.url). 例如:

node> require('url').parse('/status?name=ryan')
{ href: '/status?name=ryan',
  search: '?name=ryan',
  query: 'name=ryan',
  pathname: '/status' }

If you would like to extract the params from the query string, you can use the require('querystring').parse function, or pass true as the second argument to require('url').parse. Example:

如果你想要提取出从请求字符串(query string)中的参数,你可以用require('querystring').parse函数, 或者将true作为第二个参数传递给require('url').parse. 例如:

node> require('url').parse('/status?name=ryan', true)
{ href: '/status?name=ryan',
  search: '?name=ryan',
  query: { name: 'ryan' },
  pathname: '/status' }

message.statusCode#

Only valid for response obtained from http.ClientRequest.

仅对从http.ClientRequest获得的响应(response)有效.

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

三位数的HTTP响应状态码. 例如 404.

message.socket#

The net.Socket object associated with the connection.

与此连接(connection)关联的net.Socket对象.

With HTTPS support, use request.connection.verifyPeer() and request.connection.getPeerCertificate() to obtain the client's authentication details.

通过https的支持,使用 request.connection.verifyPeer()方法和request.connection.getPeerCertificate()方法来得到客户端的身份信息。