Skip to main content

Class: ClientRequest

Class: ClientRequest

Make HTTP/HTTPS requests.发出HTTP/HTTPS请求。

Process:进程:Main
This class is not exported from the 'electron' module. 此类不是从'electron'模块导出的。It is only available as a return value of other methods in the Electron API.它只能作为Electron API中其他方法的返回值使用。

ClientRequest implements the Writable Stream interface and is therefore an EventEmitter.实现了可写流接口,因此是一个EventEmitter

new ClientRequest(options)

  • options (Object | string) - If options is a string, it is interpreted as the request URL. 如果options是一个字符串,那么它将被解释为请求URL。If it is an object, it is expected to fully specify an HTTP request via the following properties:如果是对象,则应通过以下属性完全指定HTTP请求:
    • method string (optional) - The HTTP request method. Defaults to the GET method.HTTP请求方法。默认为GET方法。
    • url string (optional) - The request URL. 请求URL。Must be provided in the absolute form with the protocol scheme specified as http or https.必须以绝对形式提供,协议方案指定为http或https。
    • session Session (optional) - The Session instance with which the request is associated.与请求关联的Session实例。
    • partition string (optional) - The name of the partition with which the request is associated. 与请求关联的分区的名称。Defaults to the empty string. 默认为空字符串。The session option supersedes partition. session选项取代partitionThus if a session is explicitly specified, partition is ignored.因此,如果显式指定了session,则会忽略partition
    • credentials string (optional) - Can be include or omit. 可以include也可以是omitWhether to send credentials with this request. 是否随此请求发送凭据If set to include, credentials from the session associated with the request will be used. 如果设置为include,则将使用与请求关联的会话中的凭据。If set to omit, credentials will not be sent with the request (and the 'login' event will not be triggered in the event of a 401). 如果设置为omit,则不会随请求一起发送凭据(并且在401事件中不会触发'login'事件)。This matches the behavior of the fetch option of the same name. 这与同名的fetch选项的行为相匹配。If this option is not specified, authentication data from the session will be sent, and cookies will not be sent (unless useSessionCookies is set).如果未指定此选项,则将发送会话中的身份验证数据,并且不会发送cookie(除非设置了useSessionCookies)。
    • useSessionCookies boolean (optional) - Whether to send cookies with this request from the provided session. 是否从提供的会话发送带有此请求的cookie。If credentials is specified, this option has no effect. 如果指定了credentials,则此选项无效。Default is false.默认值为false
    • protocol string (optional) - Can be http: or https:. 可以是http:https:The protocol scheme in the form 'scheme:'. 形式为“scheme:”的协议方案。Defaults to 'http:'.默认为“http:”。
    • host string (optional) - The server host provided as a concatenation of the hostname and the port number 'hostname:port'.作为主机名和端口号“hostname:port”的串联提供的服务器主机。
    • hostname string (optional) - The server host name.服务器主机名。
    • port Integer (optional) - The server's listening port number.服务器的侦听端口号。
    • path string (optional) - The path part of the request URL.请求URL的路径部分。
    • redirect string (optional) - Can be follow, error or manual. 可以followerrormanualThe redirect mode for this request. 此请求的重定向模式。When mode is error, any redirection will be aborted. 当模式是error时,任何重定向都将中止。When mode is manual the redirection will be cancelled unless request.followRedirect is invoked synchronously during the redirect event. 当模式为manual时,重定向将被取消,除非在重定向事件期间同步调用request.followRedirectDefaults to follow.默认值为follow
    • origin string (optional) - The origin URL of the request.请求的原始URL。

options properties such as protocol, host, hostname, port and path strictly follow the Node.js model as described in the URL module.options属性(如protocolhosthostnameportpath)严格遵循URL模块中描述的Node.js模型。

For instance, we could have created the same request to 'github.com' as follows:例如,我们可以创建对“githubcom”的相同请求,如下所示:

const request = net.request({
method: 'GET',
protocol: 'https:',
hostname: 'github.com',
port: 443,
path: '/'
})

Instance Events实例事件

Event: 'response'

Returns:返回:

  • response IncomingMessage - An object representing the HTTP response message.表示HTTP响应消息的对象。

Event: 'login'

Returns:返回:

  • authInfo Object
    • isProxy boolean
    • scheme string
    • host string
    • port Integer
    • realm string
  • callback Function
    • username string (optional)
    • password string (optional)

Emitted when an authenticating proxy is asking for user credentials.当身份验证代理请求用户凭据时发出。

The callback function is expected to be called back with user credentials:callback应使用用户凭据进行回调:

  • username string
  • password string
request.on('login', (authInfo, callback) => {
callback('username', 'password')
})

Providing empty credentials will cancel the request and report an authentication error on the response object:提供空凭据将取消请求并报告响应对象上的身份验证错误:

request.on('response', (response) => {
console.log(`STATUS: ${response.statusCode}`);
response.on('error', (error) => {
console.log(`ERROR: ${JSON.stringify(error)}`)
})
})
request.on('login', (authInfo, callback) => {
callback()
})

Event: 'finish'

Emitted just after the last chunk of the request's data has been written into the request object.request的最后一个数据块写入request对象之后立即发出。

Event: 'abort'

Emitted when the request is aborted. request中止时发出。The abort event will not be fired if the request is already closed.如果request已关闭,则不会触发abort事件。

Event: 'error'

Returns:返回:

  • error Error - an error object providing some information about the failure.提供有关故障的一些信息的错误对象。

Emitted when the net module fails to issue a network request. 当网络模块无法发出网络请求时发出。Typically when the request object emits an error event, a close event will subsequently follow and no response object will be provided.通常,当request对象发出error事件时,随后会发生close事件,并且不会提供响应对象。

Event: 'close'

Emitted as the last event in the HTTP request-response transaction. 作为HTTP请求-响应事务中的最后一个事件发出。The close event indicates that no more events will be emitted on either the request or response objects.close事件表示不再在requestresponse对象上发出任何事件。

Event: 'redirect'

Returns:返回:

  • statusCode Integer
  • method string
  • redirectUrl string
  • responseHeaders Record<string, string[]>

Emitted when the server returns a redirect response (e.g. 301 Moved Permanently). 当服务器返回重定向响应时发出(例如301 Moved Permanently)。Calling request.followRedirect will continue with the redirection. 调用request.followRedirect将继续重定向。If this event is handled, request.followRedirect must be called synchronously, otherwise the request will be cancelled.如果处理了此事件,则必须同步调用request.followRedirect,否则该请求将被取消。

Instance Properties实例属性

request.chunkedEncoding

A boolean specifying whether the request will use HTTP chunked transfer encoding or not. 一个boolean,指定请求是否将使用HTTP分块传输编码。Defaults to false. 默认为falseThe property is readable and writable, however it can be set only before the first write operation as the HTTP headers are not yet put on the wire. 该属性是可读写的,但只能在第一次写入操作之前设置,因为HTTP标头尚未连接。Trying to set the chunkedEncoding property after the first write will throw an error.在第一次写入后尝试设置chunkedEncoding属性将引发错误。

Using chunked encoding is strongly recommended if you need to send a large request body as data will be streamed in small chunks instead of being internally buffered inside Electron process memory.如果您需要发送一个大的请求体,强烈建议使用分块编码,因为数据将以小块的形式进行流式传输,而不是在Electron进程内存中进行内部缓冲。

Instance Methods实例方法

request.setHeader(name, value)

  • name string - An extra HTTP header name.额外的HTTP标头名称。
  • value string - An extra HTTP header value.额外的HTTP标头值。

Adds an extra HTTP header. 添加一个额外的HTTP标头。The header name will be issued as-is without lowercasing. 标头名称将按原样发布,不使用小写字母。It can be called only before first write. 它只能在第一次写入之前调用。Calling this method after the first write will throw an error. 在第一次写入之后调用此方法将引发错误。If the passed value is not a string, its toString() method will be called to obtain the final value.如果传递的值不是string,则将调用其toString()方法以获得最终值。

Certain headers are restricted from being set by apps. 某些标头被应用程序限制设置。These headers are listed below. 下面列出了这些标题。More information on restricted headers can be found in Chromium's header utils.有关受限标头的更多信息,可以在Chromium的标头实用程序中找到。

  • Content-Length
  • Host
  • Trailer or Te
  • Upgrade
  • Cookie2
  • Keep-Alive
  • Transfer-Encoding

Additionally, setting the Connection header to the value upgrade is also disallowed.此外,还不允许将Connection标头设置为值upgrade

request.getHeader(name)

  • name string - Specify an extra header name.指定一个额外的标头名称。

Returns返回string - The value of a previously set extra header name.先前设置的额外标头名称的值。

request.removeHeader(name)

  • name string - Specify an extra header name.指定一个额外的标头名称。

Removes a previously set extra header name. 删除以前设置的额外标头名称。This method can be called only before first write. 此方法只能在第一次写入之前调用。Trying to call it after the first write will throw an error.在第一次写入后尝试调用它将引发错误。

request.write(chunk[, encoding][, callback])

  • chunk (string | Buffer) - A chunk of the request body's data. 请求主体的数据块。If it is a string, it is converted into a Buffer using the specified encoding.如果它是一个字符串,则会使用指定的编码将其转换为Buffer。
  • encoding string (optional) - Used to convert string chunks into Buffer objects. 用于将字符串块转换为Buffer对象。Defaults to 'utf-8'.默认为“utf-8”。
  • callback Function (optional) - Called after the write operation ends.在写入操作结束后调用。

callback is essentially a dummy function introduced in the purpose of keeping similarity with the Node.js API. 本质上是为了与Node.js API保持相似性而引入的伪函数。It is called asynchronously in the next tick after chunk content have been delivered to the Chromium networking layer. 它在chunk内容被传递到Chromium网络层后的下一个时间点被异步调用。Contrary to the Node.js implementation, it is not guaranteed that chunk content have been flushed on the wire before callback is called.与Node.js实现相反,不能保证在调用callback之前已经在连线上刷新了chunk内容。

Adds a chunk of data to the request body. 向请求正文中添加一块数据。The first write operation may cause the request headers to be issued on the wire. 第一次写入操作可能会导致在线路上发出请求标头。After the first write operation, it is not allowed to add or remove a custom header.在第一次写入操作之后,不允许添加或删除自定义标头。

request.end([chunk][, encoding][, callback])

  • chunk (string | Buffer) (optional)
  • encoding string (optional)
  • callback Function (optional)

Sends the last chunk of the request data. Subsequent write or end operations will not be allowed. 发送请求数据的最后一块。不允许进行后续的写入或结束操作。The finish event is emitted just after the end operation.finish事件在结束操作之后立即发出。

request.abort()

Cancels an ongoing HTTP transaction. 取消正在进行的HTTP事务。If the request has already emitted the close event, the abort operation will have no effect. 如果请求已经发出close事件,则中止操作将无效。Otherwise an ongoing event will emit abort and close events. 否则,正在进行的事件将发出abortclose事件。Additionally, if there is an ongoing response object,it will emit the aborted event.此外,如果有一个正在进行的响应对象,它将发出aborted的事件。

request.followRedirect()

Continues any pending redirection. Can only be called during a 'redirect' event.继续任何挂起的重定向。只能在'redirect'事件期间调用。

request.getUploadProgress()

Returns返回Object:

  • active boolean - Whether the request is currently active. 请求当前是否处于活动状态。If this is false no other properties will be set如果为false,则不会设置其他属性
  • started boolean - Whether the upload has started. If this is false both current and total will be set to 0.上传是否已开始。如果为false,则currenttotal都将设置为0。
  • current Integer - The number of bytes that have been uploaded so far到目前为止已上载的字节数
  • total Integer - The number of bytes that will be uploaded this request将上载此请求的字节数

You can use this method in conjunction with POST requests to get the progress of a file upload or other data transfer.您可以将此方法与POST请求结合使用,以获取文件上传或其他数据传输的进度。