类:http.ClientRequest


【Class: http.ClientRequest

该对象在内部创建,并由 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' 事件期间,可以向 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.】

为了向后兼容,res 只有在注册了 'error' 监听器时才会发出 'error'

【For backward compatibility, res will only emit 'error' if there is an 'error' listener registered.】

设置 Content-Length 头以限制响应主体的大小。如果 response.strictContentLength 设置为 trueContent-Length 头的值不匹配将导致抛出一个 Error,其由 code: 'ERR_HTTP_CONTENT_LENGTH_MISMATCH' 标识。

【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 的值应以字节为单位,而不是字符。使用 Buffer.byteLength() 来确定正文的字节长度。