类:http.ClientRequest
¥Class: http.ClientRequest
-
¥Extends: <http.OutgoingMessage>
此对象从 http.request()
内部创建并返回。它表示一个正在进行的请求,其标头已经排队。使用 setHeader(name, value)
、getHeader(name)
、removeHeader(name)
API 时,标头仍然是可变的。实际标头将与第一个数据块一起发送或在调用 request.end()
时发送。
¥This object is created internally and returned from http.request()
. It
represents an in-progress request whose header has already been queued. The
header is still mutable using the setHeader(name, value)
,
getHeader(name)
, removeHeader(name)
API. The actual header will
be sent along with the first data chunk or when calling request.end()
.
要获得响应,则将 'response'
的监听器添加到请求对象。当接收到响应头时,则请求对象会触发 'response'
。'response'
事件使用一个参数执行,该参数是 http.IncomingMessage
的实例。
¥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
.
在 'response'
事件期间,可以向响应对象添加监听器;特别是监听 'data'
事件。
¥During the 'response'
event, one can add listeners to the
response object; particularly to listen for the 'data'
event.
如果没有添加 'response'
句柄,则响应将被完全丢弃。但是,如果添加了 'response'
事件处理程序,则必须使用来自响应对象的数据,方法是在出现 'readable'
事件时调用 response.read()
,或者添加 'data'
处理程序,或者通过调用 .resume()
方法。在数据被消费之前,不会触发 'end'
事件。此外,在读取数据之前,它将消耗内存,最终导致 '进程内存不足' 错误。
¥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.
为了向后兼容,如果注册了 'error'
监听器,则 res
只会触发 'error'
。
¥For backward compatibility, res
will only emit 'error'
if there is an
'error'
listener registered.
设置 Content-Length
标头以限制响应正文大小。与 Content-Length
标头值不匹配将导致抛出 [Error
][Error
],由 code:
'ERR_HTTP_CONTENT_LENGTH_MISMATCH'
标识。
¥Set Content-Length
header to limit the response body size. Mismatching the
Content-Length
header value will result in an [Error
][] being thrown,
identified by code:
'ERR_HTTP_CONTENT_LENGTH_MISMATCH'
.
Content-Length
值应该以字节为单位,而不是字符。使用 Buffer.byteLength()
来确定正文的长度(以字节为单位)。
¥Content-Length
value should be in bytes, not characters. Use
Buffer.byteLength()
to determine the length of the body in bytes.